最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Validate additional role in spring-resource-server - Stack Overflow

programmeradmin3浏览0评论

Is it possible to validate 1 role with 1 Method despite on another roles?

I need to verify If client has role ONLY_READ, so he can call only GET methods and that's all for him. If someone has roles ONLY_READ and ... WRITE, so he can do everything and also if client have only WRITE so he can do everything too. When I do that, clients can not do nothing without ONLY_READ role.

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

    http
            .sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(authorize ->
                    authorize
                            .requestMatchers(NON_SECURED_PATTERNS).permitAll()
                            .requestMatchers(HttpMethod.GET).hasRole("ONLY_READ")
                            .anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(t -> t.jwtAuthenticationConverter(converter)))
            .csrf(AbstractHttpConfigurer::disable)
            .cors(AbstractHttpConfigurer::disable)
            .exceptionHandling(exceptions -> exceptions.authenticationEntryPoint(
                    new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)
            ));

    return http.build();

P.S. I found a solution, but I can not make it. It needs OrRequestMatcher where I put requestMatchers(HttpMethod.GET).hasRole("ONLY_READ") and requestMatchers("**/*"). But I can not found any class like RoleRequestMatchers

Is it possible to validate 1 role with 1 Method despite on another roles?

I need to verify If client has role ONLY_READ, so he can call only GET methods and that's all for him. If someone has roles ONLY_READ and ... WRITE, so he can do everything and also if client have only WRITE so he can do everything too. When I do that, clients can not do nothing without ONLY_READ role.

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

    http
            .sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(authorize ->
                    authorize
                            .requestMatchers(NON_SECURED_PATTERNS).permitAll()
                            .requestMatchers(HttpMethod.GET).hasRole("ONLY_READ")
                            .anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(t -> t.jwtAuthenticationConverter(converter)))
            .csrf(AbstractHttpConfigurer::disable)
            .cors(AbstractHttpConfigurer::disable)
            .exceptionHandling(exceptions -> exceptions.authenticationEntryPoint(
                    new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)
            ));

    return http.build();

P.S. I found a solution, but I can not make it. It needs OrRequestMatcher where I put requestMatchers(HttpMethod.GET).hasRole("ONLY_READ") and requestMatchers("**/*"). But I can not found any class like RoleRequestMatchers

Share Improve this question edited Mar 14 at 13:15 Dred asked Mar 14 at 11:34 DredDred 1,1308 silver badges28 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0
My workaround was like this

  @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http
                .sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(authorize ->
                        authorize
                                .requestMatchers(NON_SECURED_PATTERNS).permitAll()
                                .requestMatchers(antMatcher("**")).access(customAuthManager())
                                .anyRequest().authenticated())
                .oauth2ResourceServer(oauth2 -> oauth2.jwt(t -> t.jwtAuthenticationConverter(converter)))
                .csrf(Customizer.withDefaults())
                .cors(c -> c.configurationSource(corsConfigurationSource()))
                .exceptionHandling(exceptions -> exceptions.authenticationEntryPoint(
                        new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)
                ));

        return http.build();
    }


private AuthorizationManager<RequestAuthorizationContext> customAuthManager() {
    return (supplier, context) -> {
        final Collection<? extends GrantedAuthority> authorities = supplier.get().getAuthorities();
        if (authorities == null) {
            return new AuthorizationDecision(false);
        }

        boolean isGet = HttpMethod.GET.name().equals(context.getRequest().getMethod());
        boolean isOneRole = authorities.size() == 1;
        boolean isReadOnly = authorities.stream().anyMatch(r -> "ONLY_READ".equals(r.getAuthority()));
        boolean result = false;
        if (isGet && isOneRole && isReadOnly) {
            result = true;
        } else if (isGet && !isReadOnly) {
            result = true;
        } else if (!isOneRole) {
            result = true;
        }

        return new AuthorizationDecision(result);
    };
}
发布评论

评论列表(0)

  1. 暂无评论