如何在使用spring-security时允许特定请求

时间:2014-11-27 07:54:48

标签: java spring spring-mvc spring-security

我有一个场景,我需要让一些请求(假设请求方法是GET),这样就不会抛出401错误。

以下是我的Spring Security配置:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

     @Override
    public void configure(WebSecurity web) throws Exception {

        web.ignoring()
                .antMatchers("/bower_components/**")
                .antMatchers("/fonts/**")
                .antMatchers("/images/**")
                .antMatchers("/scripts/**")
                .antMatchers("/styles/**")
                .antMatchers("/views/**")
                .antMatchers("/i18n/**")
                .antMatchers("/swagger-ui/**")
                .antMatchers("/app/rest/register")
                .antMatchers("/app/rest/activate");
    }
}

这是我的ResourceServerConfigurerAdapter实施:

我如何允许请求?

2 个答案:

答案 0 :(得分:0)

有一种名为requestMatchers的方法,您可以使用一个或多个RequestMatcher实现来调用它。

public void configure(HttpSecurity http){
    .....

    web.ignoring().requestMatchers(new MethodTypeRequestMatcher(RequestMethod.GET));

   .....

}

您可以定义您的实施:

public class MethodRequestMatcher implements RequestMatcher {
    private RequestMethod method;

    public MethodRequestMatcher(RequestMethod method) {
        this.method = method;
    }

    @Override
    public boolean matches(HttpServletRequest request) {
        if (method == null) {
            return false;
        }
        return request.getMethod().equals(method.name());

    }
}

答案 1 :(得分:0)

 I think you can try like follows:

<code>
    @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.headers()
                    .httpStrictTransportSecurity()
                    .xssProtection()
                    .frameOptions()
            .and().authorizeRequests()
                    // PERMIT ALL
                    .antMatchers("/home").permitAll()               
                    // UNAUTHENTICATED USER
                    .antMatchers("/ForgetPassword").anonymous()
                     // TO SPECIFIC PERSON              
                    .antMatchers("/Report").access("hasRole('ADMIN') or hasRole('S_USER')");
    }
</code>