【发布时间】:2018-09-23 20:33:46
【问题描述】:
我对 Spring Security 的配置 http.anyRequest().authenticated() 的理解是任何请求都必须经过身份验证,否则我的 Spring 应用程序将返回 401 响应。
不幸的是,我的 spring 应用程序并没有这样做,而是让未经身份验证的请求通过。
这是我的 Spring 安全配置:
@Configuration
@Order(1)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationTokenFilter authenticationTokenFilter;
@Autowired
private TokenAuthenticationProvider tokenAuthenticationProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(authenticationTokenFilter, BasicAuthenticationFilter.class)
.antMatcher("/*")
.authenticationProvider(tokenAuthenticationProvider)
.authorizeRequests()
.anyRequest().authenticated();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/index.html")
.antMatchers("/error")
.antMatchers("/swagger-ui.html")
.antMatchers("/swagger-resources");
}
}
AuthenticationTokenFilter 从请求中获取 JWT 令牌,检查其有效性,从中创建身份验证,并在 SecurityContextHolder 中设置身份验证。如果没有提供令牌,SecurityContextHolder.getContext().getAuthentication() 保持为空。
我的控制器如下所示:
@RestController
@RequestMapping("/reports")
@Slf4j
public class ReportController {
@RequestMapping()
@ResponseBody
public List<String> getIds() {
log.info(SecurityContextHolder.getContext().getAuthentication());
return Collections.emptyList();
}
}
在没有令牌的情况下对端点运行 curl 请求时,我只是得到一个有效的响应:
-> curl 'localhost:8080/reports/'
[]
调试的时候可以看到SecurityContextHolder.getContext().getAuthentication()为空。
有什么想法吗?
【问题讨论】:
标签: spring spring-security jwt