spring-boot - 基于角色的授权:使用 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"
or的声明"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')"
来限制对某些端点的访问。
推荐阅读
- excel - 如果我用复制粘贴 cpde 打开另一个 Excel 工作表,VBA 宏工作停止
- python - Azure 函数要求提供 pdftotext
- lisp - ECL:文件系统不接受带有扩展字符的文件名
- r - 团体小提琴情节
- java - 如何以编程方式禁用android中其他应用程序的网络使用?
- php - 如何保护对django网站的恶意攻击
- javascript - React Native upload file using fetch, server $_FILES return object, how to access tmp_name
- php - 类名中的空格是否会导致简单 HTML DOM 出现问题?
- java - 关于java类和构造函数
- python - 输出缺少尾随换行符