REST控制器的Spring安全性

时间:2015-04-24 10:41:36

标签: spring rest spring-mvc spring-security http-basic-authentication

我正在为我的REST控制器和文档使用Spring MVC和Spring安全性。我想保护三条不同的路径:

  • “/ api / **”
  • “/ API-文档”
  • “/ API-文档”

显然,此代码仅适用于最后一个:“/ api-documentation”。我也尝试过antMatchers(“/ api / **”,“/ api-docs”,“/ api-documentation”),但我不知道如何正确配置它。有什么想法吗?

http
    .csrf().disable()
    .exceptionHandling().authenticationEntryPoint(entryPoint())
    .and()                  
    .antMatcher("/api/**")            
    .antMatcher("/api-docs") 
    .antMatcher("/api-documentation") 
    .authorizeRequests()
    .anyRequest().hasRole("REST")
    .and()
    .httpBasic();

3 个答案:

答案 0 :(得分:0)

您必须指定谁可以访问指定的路径:

.antMatchers("/api/**").permitAll() 
.antMatchers("/api-docs").hasRole("ADMIN")

答案 1 :(得分:0)

以下是一些路径匹配建议。

"/api/**"将匹配/api/x/y等所有方法。

"/api-docs"只会与/api-docs匹配。同样/api-documentation

如果您添加"/api-docs/*",则会映射/api-docs/x

以下是关于蚂蚁模式的some useful resources

因此,像

http
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(entryPoint())
.and()                  
.antMatchers("/api/**","/api-docs","/api-documentation")
.authorizeRequests()
.anyRequest().hasRole("REST")
.and()
.httpBasic();

必须按照您的路径规范要求工作。

答案 2 :(得分:0)

对于这种情况,只需要将antmatcher更改为.antMatcher("/api*")删除其他两个。