Spring Security中未触发JWT身份验证过滤器

时间:2018-06-23 14:49:53

标签: java spring spring-mvc spring-boot spring-security

我已经为我的Spring Rest后端创建了JWT身份验证过滤器。创建JWT似乎不是问题,但是对于我当前的设置,任何请求都经过了身份验证,尽管客户端没有在标头中传递任何令牌,但没有任何请求会触发401。

我的WebSecurityConfig:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true,
    jsr250Enabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

private JwtAuthenticationEntryPoint unauthorizedHandler;

private CustomUserDetailsService customUserDetailsService;

@Autowired
public WebSecurityConfig(final JwtAuthenticationEntryPoint unauthorizedHandler,
                         final CustomUserDetailsService customUserDetailsService) {
    this.unauthorizedHandler = unauthorizedHandler;
    this.customUserDetailsService = customUserDetailsService;
}

@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
    return new JwtAuthenticationFilter();
}

@Bean
public JwtAuthenticationSuccessHandler jwtAuthenticationSuccessHandler() {
    return new JwtAuthenticationSuccessHandler();
}

@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
    authenticationManagerBuilder
            .userDetailsService(customUserDetailsService)
            .passwordEncoder(passwordEncoder());
}

@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

/**
 * {@inheritDoc}
 */
@Override
protected void configure(final HttpSecurity http) throws Exception {

    http
            .csrf()
            .disable()
            .cors()
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(unauthorizedHandler)
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .antMatcher("/api")
            .authorizeRequests()
            .anyRequest()
            .authenticated()

            .and()
            .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}

/**
 * Sets security evaluation context.
 *
 * @return {@link SecurityEvaluationContextExtension}
 */
@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
    return new SecurityEvaluationContextExtension();
}
}

我已经设置好所有请求都需要授权。我的JwtAuthenticationEntryPoint符合预期:抛出一般401错误。

我的JwtAuthenticationFilter:

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

@Autowired
private JwtTokenProvider tokenProvider;

@Autowired
private CustomUserDetailsService customUserDetailsService;

private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain
        filterChain) throws ServletException, IOException {

    logger.debug("Filtering request for JWT header verification");

    try {
        String jwt = getJwtFromRequest(request);

        if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
            String username = tokenProvider.getUserIdFromJWT(jwt);

            UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken
                    (userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    } catch (Exception ex) {
        logger.error("Could not set user authentication in security context", ex);
    }

    filterChain.doFilter(request, response);
}

private String getJwtFromRequest(HttpServletRequest request) {

    logger.debug("Attempting to get token from request header");

    String bearerToken = request.getHeader("Authorization");
    if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
        return bearerToken.substring(7, bearerToken.length());
    }
    return null;
}
 }

1 个答案:

答案 0 :(得分:-1)

发现了问题。

我必须在我的web.xml文件中包含对该过滤器的引用,但是使用组件扫描程序不会自动获取该过滤器。

类似:

<filter>
    <filter-name>jwtFilter</filter-name>
    <filter-class>com.path.to.JwtFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>jwtFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>