【发布时间】:2020-01-31 23:15:09
【问题描述】:
我正在使用 Spring Boot 设置资源服务器并保护我使用 Spring Security 提供的 OAuth2 的端点。所以我使用的是 Spring Boot 2.1.8.RELEASE,例如使用 Spring Security 5.1.6.RELEASE。
作为授权服务器,我正在使用 Keycloak。资源服务器中身份验证、颁发访问令牌和验证令牌之间的所有过程都正常工作。下面是一个发行和解码的令牌的例子(有些部分被剪掉了):
{
"jti": "5df54cac-8b06-4d36-b642-186bbd647fbf",
"exp": 1570048999,
"aud": [
"myservice",
"account"
],
"azp": "myservice",
"realm_access": {
"roles": [
"offline_access",
"uma_authorization"
]
},
"resource_access": {
"myservice": {
"roles": [
"ROLE_user",
"ROLE_admin"
]
},
"account": {
"roles": [
"manage-account",
"manage-account-links",
"view-profile"
]
}
},
"scope": "openid email offline_access microprofile-jwt profile address phone",
}
如何配置 Spring Security 以使用访问令牌中的信息为不同的端点提供条件授权?
最终我想写一个这样的控制器:
@RestController
public class Controller {
@Secured("ROLE_user")
@GetMapping("userinfo")
public String userinfo() {
return "not too sensitive action";
}
@Secured("ROLE_admin")
@GetMapping("administration")
public String administration() {
return "TOOOO sensitive action";
}
}
【问题讨论】:
-
我遇到了同样的问题,我正在尝试使用自定义的 JwtDecoder 和 CustomAccessTokenConverter,但仍然没有运气。关键应该是将 resource_access 角色放置在 Spring Security 可以获取它们的地方,但到目前为止,我没有运气,即使遵循互联网上的多个教程/示例。
-
一些见解可以在这个视频中找到:youtube.com/… 这个播放列表包含实际上很好的材料,可以更好地了解如何构建 SpringBoot 应用程序。
标签: spring rest spring-boot spring-security authorization