2017-08-08 161 views
0

我想使用弹簧安全来确保使用JWT令牌的休息/无状态api。从我看到的研究中,它涉及到关闭春季安全会话管理,然后添加一些自定义过滤器来处理用户登录以及检查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都会打印“in here”。我只希望在localhost:8080/api/order时看到这条消息,但当我到localhost:8080/api/user时,我会看到它。

有没有办法得到这种行为?

回答

0

您配置的方式,HttpSecurity将应用于包括用户端点在内的所有URL。 authorizeRequests() .antMatchers("/api/user").permitAll()行不会阻止来自认证过滤器的“用户”端点被调用。 它只是说任何经过验证的用户都可以调用它。 您只需将过滤器应用于“订购”端点。像这样: http .requestMatchers().antMatchers("/api/user") .and() .authorizeRequests()

+0

我试过了

配置(Websecurity)方法和它的工作!我还看到你可以重写configure(Websecurity)方法并使用ignore()方法忽略端点。我不确定哪种方式是首选。 – tfecw

0

@ tsolakp's answer sorta适合我。我结束了重写虽然

@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) 
    ; 
    }