为什么我的春季安全性配置无法正常工作,我期望如何?

时间:2018-08-08 18:55:49

标签: java spring rest security spring-security

我有问题...我有一个SecurityConfig.class,就像这样(这是WebSecurityConfigurerAdapter的扩展类):

/**
 * This method define which resources are public and which are secured
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().authorizeRequests()
            .antMatchers(HttpMethod.POST, SecurityConstants.SIGN_UP_URL).permitAll().anyRequest()
            .authenticated()
            .and().addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthorizationFilter(authenticationManager()))         .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

但是我的问题是,当我尝试访问SIGN_UP_URL时,应用程序正尝试使用此过滤器对用户进行身份验证:

@Override
protected void doFilterInternal(HttpServletRequest req,
                                HttpServletResponse res,
                                FilterChain chain) throws IOException, ServletException {
    String header = req.getHeader(SecurityConstants.HEADER_STRING);

    if (header == null || !header.startsWith(SecurityConstants.TOKEN_PREFIX)) {
        chain.doFilter(req, res);
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED,"Access Denied");
        return;
    }

    UsernamePasswordAuthenticationToken authentication = getAuthentication(req);

    SecurityContextHolder.getContext().setAuthentication(authentication);
    chain.doFilter(req, res);
}

检查此时的标头为空(因为从理论上来说,URL不需要身份验证或任何令牌)应该不会发生,有人可以帮我吗?当我对所有用户开放未经身份验证的安全性时,该方法将成功执行

1 个答案:

答案 0 :(得分:0)

您必须在SecurityConfig.class中添加一个方法

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(HttpMethod.POST, SecurityConstants.SIGN_UP_URL);
}

通过这种方法,您可以将不喜欢的网址转到安全过滤器。