【问题标题】:Securing endpoints in Spring Boot by rights/roles通过权限/角色保护 Spring Boot 中的端点
【发布时间】:2017-05-23 09:49:44
【问题描述】:
@RestController
public class AccountController {

    @PermitAll
    @RequestMapping(value = "/test")
    public ResponseEntity<String> test() {
        // ...
    }

    @RolesAllowed("ROLE_ADMIN)
    @RequestMapping(value = "/products")
    public ResponseEntity<List<Product>> products() {
        // ...
    }
}

如何配置 Spring Boot 以无需身份验证即可访问“/test”,但可以通过身份验证和检查权限/角色访问“/products”?

是否可以在配置中不提及@PermitAll(如“/test”)的路径?

【问题讨论】:

  • 您是否尝试过自定义 WebSecurityConfigurerAdapter
  • 不。你有例子吗?

标签: java spring spring-mvc spring-boot spring-security


【解决方案1】:

问题:Spring Boot 无需身份验证即可访问“/test”,但通过身份验证访问“/products”
解决方案

http.authorizeRequests().antMatchers("/test").permitAll()
.antMatchers("/products").hasRole("ADMIN").anyRequest().authenticated().and().httpBasic();

注意:默认情况下,当你添加spring security时,它会要求对所有url进行身份验证,你需要指定一个不需要身份验证的url。例如 /login 应该是 permitAll。

Click here for Source code of security configuration

更多匹配器示例请参考 Sample HttpSecurity 示例,如下所示,

更多详情:https://docs.spring.io/spring-security/site/docs/current/reference/html/jc.html

【讨论】:

  • 是否可以在配置中不提及@PermitAll(如“/test”)的路径?我不想在控制器和配置中两次提及“/test”。
  • 如果您在 WebSecurityConfig 中为路径配置 HttpSecurity,那么您不需要在控制器部分添加任何内容。
  • 甚至@RequestMapping?那么spring怎么会知道调用什么方法呢?
  • 假设您的方法是 @RequestMapping(value = "/saveUser", method = RequestMethod.POST) 并且如果您有 antMatchers("/saveUser").hasRole("ADMIN").anyRequest ().authenticated() 然后 spring 从配置中知道它需要身份验证和要检查的角色。 Spring 有 url 和方法映射。在控制台上,您可以在服务器启动时看到映射。例如将“{[/alerts],methods=[POST]}”映射到公共 com.test.model.Alert com.mynet.AlertController.addalert(com.test.model.Alert)
  • 请提供您的 git 代码链接。我会看看的。
【解决方案2】:

您可以提供下一个配置类。在这种情况下,如果不受注释限制,一切都可以访问。

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().anyRequest().permitAll();
    }

}

查看SecurityConfig class here 了解更多配置选项。

【讨论】:

  • 身份验证怎么样,您能否提供一个具有身份验证和@PermitAll/@RolesAllowed 的示例?谢谢。
  • 您能否描述一下身份验证的确切含义?使用此配置,您可以使用 @Secured 注释控制访问。如需更完整的安全配置(使用自定义 UserDetailsS​​erviceImp),请查看答案中的链接 (stackoverflow.com/questions/43861189/…)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 2020-06-01
  • 2020-12-20
  • 2020-11-30
  • 2021-08-02
  • 2021-04-28
相关资源
最近更新 更多