spring-security Spring安全性无法从JWT中提取角色

kcugc4gi  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(170)

我正在为我的Oauth服务器使用FusionAuth,我遇到了一个问题。Spring安全将成功解码JWT,但没有角色!
这是我的JSON格式的完整身份验证对象:
https://jsoneditoronline.org/#left=cloud.911cb58e717544ab9168632ed221aae1
正如你所看到的,我在我的主体中有角色和角色对象。但是当我试图在@PreAuthroize中使用它或者甚至记录它时,它是空的。
Web安全配置器适配器:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests(authorizeRequests ->
                        authorizeRequests
                                .antMatchers(HttpMethod.GET, "v1/balance/**").permitAll()
                                .antMatchers(HttpMethod.POST, "v1/balance/**").permitAll()
                                .antMatchers(HttpMethod.GET, "/actuator/**").permitAll()
                                .anyRequest().authenticated()
                )
                .oauth2ResourceServer(oauth2ResourceServer ->
                        oauth2ResourceServer
                                .jwt(jwt ->
                                        jwt.decoder(JwtDecoders.fromIssuerLocation(issuerUri)).jwkSetUri(jwksUrl)
                                )
                );

    }

这是我尝试记录角色的方式:

@GetMapping("/currency/{currency}")
//    @PreAuthorize("hasAnyRole('admin')")
    public CurrencyBalance getWalletByCurrency(@PathVariable String currency, Principal principal){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        Set<String> roles = authentication.getAuthorities().stream()
                .map(r -> r.getAuthority()).collect(Collectors.toSet());
        System.out.println(roles);
        System.out.println(new Gson().toJson(authentication));
        System.out.println(authentication.getAuthorities());
        System.out.println(authentication.getCredentials().toString());
        System.out.println(authentication.getDetails());
        System.out.println(authentication.getPrincipal());
        System.out.println(authentication.getName());
        return null;
//        return balanceService.getWalletByCurrency(principal.getName(),currency);
    }
a11xaf1n

a11xaf1n1#

首先,您需要了解JWT身份验证是如何工作的

(来源:spring.io
JwtAuthenticationConverter将JWT转换为身份验证权限,默认情况下,它只将JWT的SCOPE解码为权限。(请查看JwtGrantedAuthoritiesConverter)。
如果要对JWT的自定义属性进行解码,则必须创建JwtAuthenticationConverter的子类并覆盖extractAuthorities方法。

相关问题