我正在构建一个标准的 spring boot mvc + thymeleaf + Oauth2。到目前为止,我添加了 oauth2-client 库用于身份验证目的,但现在我需要授权来保护我的应用程序。
这是否意味着我还需要将其配置为资源服务器?
如果不是,我如何从我的授权服务器将角色放入的私有(private)声明(在 ID token 中)映射权限?
最佳答案
资源服务器配置经过调整以保护 REST 资源。
除非您公开 API,否则客户端配置就很好。如果是这样,请添加第二个安全过滤器链。其他答案中的详细信息:Use Keycloak Spring Adapter with Spring Boot 3
OAuth2 客户端中的权限映射
正如我在评论中提到的,Spring-security documentation总是比 Stackoverflow 上的任何人写的都要好(当然还有 Spring 安全团队成员,他们碰巧发布了答案)
仔细检查授权服务器将用户角色放入其中的声明并提供权限映射器,可以是:
- 明确使用
http.oauth2Login().userInfoEndpoint().userAuthoritiesMapper(userAuthoritiesMapper());
- 作为
GrantedAuthoritiesMapper
类型的@Bean
,应由 spring-boot 自动配置
在这两种情况下,映射器的代码是相同的(使用授权服务器仔细检查用户角色的声明名称,但对于 Azure AD,它可能是组
):
@Bean
GrantedAuthoritiesMapper userAuthoritiesMapper() {
return (authorities) -> {
Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
authorities.forEach(authority -> {
if (authority instanceof OidcUserAuthority oidcAuth) {
oidcAuth.getIdToken().getClaimAsStringList("groups").forEach(a -> mappedAuthorities.add(new SimpleGrantedAuthority(a)));
} else if (authority instanceof OAuth2UserAuthority oauth2Auth) {
((List<String>) oauth2Auth.getAttributes().getOrDefault("groups", List.of())).forEach(a -> mappedAuthorities.add(new SimpleGrantedAuthority(a)));
}
});
return mappedAuthorities;
};
}
关于java - 如何在 spring-boot OAuth2 客户端中映射权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75439875/