我对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() 保持为 null。
我的控制器看起来像这样:
@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()
一片空白。
有任何想法吗?
它实际上按预期工作,这取决于您编写配置的方式。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(authenticationTokenFilter, BasicAuthenticationFilter.class)
.antMatcher("/*")
.authenticationProvider(tokenAuthenticationProvider)
.authorizeRequests()
.anyRequest().authenticated();
}
这是您自己的配置,由我进行了一些额外的缩进。当你写一个antMatcher
这意味着接下来的一切antMatcher
适用于其中写入的路径/表达式(请参阅 JavadocAntPathMatcher https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html).
现在正如你所写的/*
这适用于/reports
它不适用于/reports/
(是的,最后/
很重要!)。
你可能想写的是
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(authenticationTokenFilter, BasicAuthenticationFilter.class)
.antMatcher("/**")
.authenticationProvider(tokenAuthenticationProvider)
.authorizeRequests()
.anyRequest().authenticated();
}
注意/**
代替/*
。然而,这基本上与省略相同antMatcher
并简单地写
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(authenticationTokenFilter, BasicAuthenticationFilter.class)
.authenticationProvider(tokenAuthenticationProvider)
.authorizeRequests()
.anyRequest().authenticated();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)