首页 文章

通过权限/角色保护Spring Boot中的 endpoints

提问于
浏览
0
@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”)的路径?

2 回答

  • -1

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

    @EnableWebSecurity
    @EnableGlobalMethodSecurity(securedEnabled = true)
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests().anyRequest().permitAll();
        }
    
    }
    

    检查SecurityConfig class here以获取更多配置选项 .

  • -1

    Question :Spring Boot能够访问"/test"而无需身份验证,但"/products"具有身份验证
    Solution

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

    Note :默认情况下,当您添加spring security时,它会要求对所有URL进行身份验证,并且您需要指定不需要身份验证的URL . 例如/ login应该是permitAll .

    Click here for Source code of security configuration

    有关更多匹配器的示例,请参阅示例HttpSecurity示例,如下所示,

    Refer

    有关详细信息:https://docs.spring.io/spring-security/site/docs/current/reference/html/jc.html

相关问题