java - Spring Security PermitAll() 与排除 url 不匹配

标签 java spring spring-boot spring-security spring-security-oauth2

我使用 spring-boot 和集成的 Outh2 spring security 做了 API。 我有更多以/api/v1/开头的 API 端点。我需要验证除 API/api/v1/test-data 之外的所有 API。

我的Resourceserver http配置如下。

@Override
    public void configure(HttpSecurity http) throws Exception {
       http.
                anonymous().disable()
                .authorizeRequests()
                .antMatchers("/api/v1/**").hasRole("API_ACCESS")
                .antMatchers("/api/v1/test-data").permitAll()
                .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
    } 

但是.antMatchers("/api/v1/test-data").permitAll()不适合我,但 .antMatchers("/api/v1/**").hasRole("API_ACCESS")适用于“/api/v1/”下的所有端点。

我的休息 Controller 是

@RestController
@RequestMapping(path="/api/v1")
public class HotelController {

    @Autowired
    private HotelService service;
    @Autowired
    private APIAuthService authservice; 

    @GetMapping("/hotels")
    public ResponseEntity<Map<String,Object>> hotelsGet(@RequestParam(value = "page", defaultValue="1", required = false) Integer page, @RequestParam(value = "size", defaultValue="25", required = false) Integer size
            , @RequestParam(value = "orderby", defaultValue="hotelname", required = false) String orderby, @RequestParam(value = "order", defaultValue="asc", required = false) String order) {
        return this.service.list(page,size,orderby,order);
    }

    @GetMapping("/test-data")
    public String hotelsGetTest(@RequestParam(value = "page", defaultValue="1", required = false) Integer page, @RequestParam(value = "size", defaultValue="10", required = false) Integer size) {
        return "tested";
    }

    @GetMapping("/baseauth")
    public boolean baseauth(@RequestHeader(value = "authorization", required = true) String authString) {
        return this.authservice.isUserAuthenticated(authString);
    }

}

如何从“hasRole”检查中排除“/api/v1/test-data”?

最佳答案

交换你的规则:

            .antMatchers("/api/v1/test-data").permitAll()
            .antMatchers("/api/v1/**").hasRole("API_ACCESS")

顺序很重要。

关于java - Spring Security PermitAll() 与排除 url 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49015355/

相关文章:

java - Spring @ModelAttribute 接口(interface)

java - 如何在 Controller 中将 RequestBody 定义为列表,我收到 500 错误

java - 将 Java 对象转换为 JsonObject

java - 从 String[] 中提取数字

json - Spring MVC jackson 异常处理

java - 如何在 Spring Boot 测试中禁用 `@EnableKafka`?

java - 找不到 Gradle 构建工具.jar

java - 如何使用或运算符进行 HQL 查询

java - 可以修改sql中的唯一约束吗?

java - TestNg + Spring Integration如何抽象beforeMethod