禁用特定URL Spring的基本身份验证

时间:2017-04-15 16:47:10

标签: java spring authentication

我是Spring新手,我需要为我的其他控制器的8/10个URL启用基本身份验证,而其他2个应该可以在没有任何基本身份验证的情况下访问。 我正在使用gradle来构建应用程序,因此没有涉及的xml文件。 (我看到一些带有web.xml的解决方案,我没有一个) 这是我的网络安全配置:

 @Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.ignoring().antMatchers("/abcd/**");

    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("user").password("password");

    }
}

这是我的控制器:

    @RestController
@RequestMapping(value = "/abcd")
public class PaymentController implements ElasticSearchConstants {

    @RequestMapping(value = "/sample", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public static void authExpemtedController(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //do something
    }
}

我尝试了web.ignoring()。antMatchers(" / abcd /");没有帮助。当我从邮递员那里尝试时,我总是收到401错误: {   "时间戳":1492274727955,   " status":401,   "错误":"未经授权",   " message":"访问此资源需要完全身份验证",   "路径":" / abcd / sample" }

我需要公开这样的API,不需要任何身份验证,而其他API需要进行身份验证。

感谢您的帮助

更新: 我知道http.authoriseRequest()。antMatchers(" / abcd")。permitAll() 此方法仅允许任何用户访问。我不想将任何用户信息传递给此API。

1 个答案:

答案 0 :(得分:2)

您可能需要参考Section 5.4 Authorize Requests of the Spring Security docs

  

我们的示例仅要求用户进行身份验证,并且已针对应用程序中的每个URL进行了身份验证。我们可以通过向http.authorizeRequests()方法添加多个子项来指定URL的自定义要求。例如:

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()                                                                                    
            .antMatchers("/resources/**", "/signup", "/about").permitAll()                                  
            .antMatchers("/admin/**").hasRole("ADMIN")                                                  
            .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")                        
            .anyRequest().authenticated()
            .and()
        // ...
        .formLogin();
}
相关问题