我尝试使用Spring安全性来保护使用JWT令牌的rest / stateless api。从我已经看到的研究中,它涉及关闭Spring安全会话管理,然后添加一些自定义过滤器来处理用户登录以及检查jwt令牌。
我遇到的问题是,一旦我添加了一个过滤器,它就可以在每个过滤器上运行,而不仅仅是我想要的端点。我需要打开登录端点以及其他一些便于注册和不需要保护的参考数据的端点。
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/user").permitAll()
.anyRequest().authenticated().and()
.addFilterBefore(new StatelessAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
;
}
}
所有StatelessAuthenticationFilter都在这里打印""。当你去localhost:8080 / api / order时,我只希望看到该消息打印,但是当你去localhost:8080 / api / user时我看到它出现了。
有没有办法解决这个问题?
答案 0 :(得分:0)
您配置的方式,HttpSecurity
将应用于包括用户端点在内的所有网址。
authorizeRequests() .antMatchers("/api/user").permitAll()
行不会阻止“用户”端点调用身份验证过滤器。
它只是说任何经过身份验证的用户都可以调用它。
您只需将过滤器应用于“订购”端点。像这样:
http .requestMatchers().antMatchers("/api/user") .and() .authorizeRequests()
。
答案 1 :(得分:0)
@ tsolakp的回答sorta对我有用。我最终压倒了
配置(Websecurity)方法
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/api/user");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated().and()
.addFilterBefore(new StatelessAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
;
}