如何解决基于角色的授权:具有OneLogin和Spring Security的Oauth
我有一个Spring Boot应用程序,该应用程序将Oauth与OneLogin一起用作授权服务器。 现在,我想实现基于角色的授权,以仅向具有某些特权的用户公开某些API。
我有属于组的用户。假设用户A属于“ admin”组,而用户B不属于admin组。我的问题是如何使用这些组仅使用户A访问某些API。
这是有关经过身份验证的用户的信息以供参考:
authorities
0
authority "ROLE_USER" **//says ROLE_USER even when the user belongs to the admin group**
attributes
at_hash "xxxxx"
sub "xxxx"
iss "https://******/oidc/2"
groups
0 "Group A"
1 "Group B"
2 **"DEMO"**
3 **"DEMO Admin"** **//presence in this group should be considered for authorisation**
preferred_username "xxx"
given_name "xxxx"
nonce "xxxxxxx"
sid "xxxxxxx"
aud
0 "xxxxxxx"
updated_at "xxxxxx"
name "xxxxxx"
exp "xxxxxxx"
family_name "xxxxxx"
iat "xxxxxxxx"
email "xxxxxxxx"
idToken {…}
userInfo {…}
1
authority "SCOPE_email"
2
authority "SCOPE_groups"
3
authority "SCOPE_openid"
4
authority "SCOPE_profile"
我想保护我的休息控制器这样的东西:
@PreAuthorize("Belongs to group admin")
@RequestMapping(value = "/delete",method = RequestMethod.GET)
public string delete() {
System.out.println("delete");
}
这是我的application.yaml文件
server:
servlet:
context-path: /demo
spring:
security:
oauth2:
client:
registration:
onelogin:
client-id: *****
client-secret: *******
scope: openid,profile,email,groups
provider: onelogin
provider:
onelogin:
issuer-uri: https://******/oidc/2
解决方法
由于您的应用程序也是资源服务器,因此可以使用自定义JwtAuthenticationConverter
来配置JWT如何转换为Authentication
对象。专门针对这种情况,您可以配置如何将JWT转换为GrantedAuthorities
的列表。
默认情况下,资源服务器根据GrantedAuthorities
声明填充"scope"
。
如果JWT包含一个名称为"scope"
或"scp"
的声明,那么Spring Security将使用该声明中的值通过在每个值前面加上"SCOPE_"
来构造权限。这就是为什么您看到权限“ SCOPE_email”,“ SCOPE_groups”等
如果您想改为基于“组”声明填充GrantedAuthorities
,则可以这样做:
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(new CustomJwtGrantedAuthoritiesConverter());
return converter;
}
public class CustomJwtGrantedAuthoritiesConverter implements Converter<Jwt,Collection<GrantedAuthority>> {
@Override
public Collection<GrantedAuthority> convert(Jwt jwt) {
Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
for (String group : getGroups(jwt)) {
grantedAuthorities.add(new SimpleGrantedAuthority(group));
}
return grantedAuthorities;
}
}
private Collection<String> getGroups(Jwt jwt) {
Object groups = jwt.getClaim("groups");
// Convert groups to Collection of Strings based on your logic
}
然后,您可以使用表达式"hasAuthority('YOUR_CUSTOM_GROUP_NAME')"
限制对某些端点的访问。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。