0

我想保护REST API。规则很简单。使用Spring Security限制端点的身份验证方法

  • 用户必须拨打/api/authenticate获得令牌
  • ,用户可以使用令牌(从/api/authenticate收到)来访问API /api/**
  • 端点/api/authenticate只接受HTTP基本身份验证(无令牌认证)
  • 端点/api/**(不含/api/authenticate)只接受令牌认证(无基本身份验证)
  • 所有其余端点是公开的,不需要authe ntication。

实际上我用这样的:

@Configuration 
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

     @Autowired 
     private TokenAuthenticationProvider tokenAuthenticationProvider; 

     @Override 
     protected void configure(final HttpSecurity httpSecurity) throws Exception { 
      httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 
      httpSecurity.headers().disable(); 
      httpSecurity.setSharedObject(TokenAuthenticationProvider.class, this.tokenAuthenticationProvider); 
      httpSecurity.antMatcher("/api/authenticate").httpBasic(); 
      httpSecurity.antMatcher("/api/**").apply(new TokenAuthenticationConfigurer()); 
      httpSecurity.authorizeRequests() 
        .antMatchers("/api/**").authenticated() 
        .anyRequest().permitAll(); 
     } 
    } 

其实,如果我发送一个请求与令牌/api/authenticate我的配置接受请求。我认为这是因为/api/authenticate/api/**的一部分。所以我需要排除这个路径进行令牌认证。

我该怎么做?

编辑1

如果我使用.and()流畅的风格,结果是完全一样的。

@Override 
    protected void configure(final HttpSecurity httpSecurity) throws Exception { 
     httpSecurity.setSharedObject(TokenAuthenticationProvider.class, this.tokenAuthenticationProvider); 
     httpSecurity 
       .headers().disable() 
       .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) 
       .and() 
       .antMatcher("/api/authenticate").httpBasic() 
       .and() 
       .antMatcher("/api/**").apply(new TokenAuthenticationConfigurer()) 
       .and() 
       .authorizeRequests().antMatchers("/api/**").authenticated().anyRequest().permitAll(); 
    } 

编辑2

据我所知的SecurityBuilderHttpSecurity),在configure(...)方法的antMatcher(...)每个呼叫将覆盖先前的呼叫。在调试日志中,我可以看到,Spring Security始终尝试将请求路径与/api/**匹配,但从未再次登录/api/authenticate。如果我切换订单,我无法再访问该API,只需/api/authenticate,因为Spring Security现在总是尝试再次匹配/api/authenticate

所以,问题是:我如何可以注册多个规则:

  • /api/authenticate - >HttpBasicConfigurer.http()
  • /api/** - >TokenAuthenticationConfigurer(我的令牌认证配置,.apply(...)
+0

你管理来解决这个问题? –

+0

是的。您必须通过扩展'WebSecurityConfigurerAdapter'来创建多个安全配置。一个配置为'/ api/authenticate',另一个为'/ api/**'。他们每个人都可以配置所需的安全机制。您还必须使用'@ Order'来定义安全配置的优先级。 – baymon

回答

相关问题