【发布时间】:2018-03-24 19:44:29
【问题描述】:
我有一个通过 JWT 进行身份验证的 Spring Boot REST API。我的问题是我已将 Spring Security 配置为允许不受限制地访问用于验证 /auth/token 的路径,但它仍然会在不应该出现的情况下击中我的安全过滤器。不知道我在哪里错了,任何建议都非常适合
安全配置
public class JwtWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private UserDetailsService userDetailsService;
@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder)
throws Exception {
authenticationManagerBuilder
.userDetailsService(this.userDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public JwtAuthenticationFilter authenticationTokenFilter() throws Exception {
return new JwtAuthenticationFilter();
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeRequests()
.antMatchers("/auth/token").permitAll() // do not authenticate
.anyRequest().authenticated()
// TODO: configure
.cors()
.and()
// TODO enable and configure
.csrf().disable()
// Unauthorized request handler
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
// Keep application security stateless
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// JWT security filter
httpSecurity.addFilterBefore(authenticationTokenFilter(),
UsernamePasswordAuthenticationFilter.class);
// Disable page caching to prevent cached REST responses
httpSecurity.headers().cacheControl();
}
@Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity.ignoring().antMatchers(HttpMethod.POST, "/auth/token");
}
}
过滤器
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
// this runs
}
}
控制器
@RestController
public class AuthenticationController {
// Authenticate user
@RequestMapping(value = "/auth/token", method = RequestMethod.POST)
public ResponseEntity<?> createAuthenticationToken(HttpServletResponse response,
@RequestBody JwtAuthenticationRequest authenticationRequest, Device device) throws AuthenticationException {
// never gets to run
}
}
【问题讨论】:
标签: java spring-mvc spring-security