允许特定角色访问一组有限的 URI,但让其余角色访问所有 URI

问题描述 投票:0回答:1

我在授权具有角色 ROLE_CUSTOMER 的用户仅访问下面列出的这些 URI 集时遇到问题:

POST /api/v1/beneficiaries/check 
GET /api/v1/accounts/{accountId}/beneficiary-accounts  
GET /api/v1/accounts/{idAccount} 
GET /api/v1/cards/{cardId}
PUT /api/v1/cards/{cardId}/deactivate

但不适用于剩余的 URI

并允许具有角色(ROLE_API、ROLE_USER)的其他用户访问所有 URI,他们应该只是经过身份验证。

我如何通过 antMatchers 配置来实现这一点。

我已经尝试了几次以下配置:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/api/v1/api-docs/**").permitAll()
                .antMatchers("/api/v1/api-docs**").permitAll()
                .antMatchers("/api/v1/auth").permitAll()
                .antMatchers("/api/v1/auth-dejamobile").permitAll()
                .antMatchers("/api/v1/hc").permitAll()
                .antMatchers("/api/v1/dictionaries/**").permitAll()
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/api/v1/beneficiaries/check").hasRole("CUSTOMER")
                .antMatchers("/api/v1/accounts/*/beneficiary-accounts").hasRole("CUSTOMER")
                .antMatchers("/api/v1/accounts/*").hasRole("CUSTOMER")
                .antMatchers("/api/v1/cards/*").hasRole("CUSTOMER")
                .antMatchers(HttpMethod.PUT,"/api/v1/cards/*/deactivate").hasRole("CUSTOMER")
                .and()
                .authorizeRequests()
                .antMatchers("/**").not().hasRole("CUSTOMER")
                .anyRequest().authenticated();


        http
        .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
    }

但是 ROLE_APIROLE_USER 无法访问上述五个 URI,并且 ROLE_CUSTOMER 无法访问 PUT /api/v1/cards/{cardId}/deactivate !!

非常感谢任何帮助。

java spring spring-boot spring-security rbac
1个回答
0
投票

在编写 Spring Security 匹配规则时,规则的顺序很重要,因为它们定义的顺序也是它们被查阅的顺序!所以

.antMatchers("/api/v1/cards/*").hasRole("CUSTOMER")
也已经适用于 PUT 了(在这个下面)。

接下来,您的安全规则是“允许访问所有经过身份验证的用户或 hasRole 客户”,然后编写该规则。使用类似

access("hasRole('CUSTOMER') or isAuthenticated())
的内容。虽然这个规则有点奇怪,因为在这种特定情况下只有
isAuthenticated
才能达到目的。

© www.soinside.com 2019 - 2024. All rights reserved.