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

时间:2017-05-23 09:49:44

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

@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以便能够访问&#34; / test&#34;没有身份验证,但&#34; / products&#34;具有身份验证和检查权限/角色?

在配置中是否可以不提及@PermitAll的路径(例如&#34; / test&#34;)?

2 个答案:

答案 0 :(得分:-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 :(得分:-1)

问题:Spring Boot能够访问&#34; / test&#34;没有身份验证,但&#34; / products&#34;与认证
解决方案

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

注意:默认情况下,当您添加spring security时,它会要求对所有网址进行身份验证,您需要指定不需要身份验证的网址。例如/ 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