我已将CAS配置为OAuth2服务器。成功登录后,它将返回JWT,但JWT中的角色字段始终为空,例如;
{
"sub": "dg",
...
"roles": [],
"nonce": "",
"client_id": "first-client",
"credentialType": "UsernamePasswordCredential",
...
}
我登录时如何在JWT中获取身份验证的用户角色并将其放置在JWT中?
这是我的示例服务注册表;
{
"@class" : "org.apereo.cas.support.oauth.services.OAuthRegisteredService",
"serviceId" : "http://localhost:8085/.*",
"name" : "CAS Spring Secured App",
"description": "This is a Spring App that usses the CAS Server for its authentication",
"id" : 1,
"evaluationOrder" : 1,
"bypassApprovalPrompt": true,
"jwtAccessToken": true,
"clientId": "first-client",
"clientSecret": "noonewilleverguess",
"supportedGrantTypes": [ "java.util.HashSet", [ "authorization_code" ] ],
"supportedResponseTypes": [ "java.util.HashSet", [ "code" ] ]
}
感谢您的帮助。
我找到了解决方案。来自CAS博客(https://apereo.github.io/2017/02/22/cas51-dbauthn-tutorial/),
今天,CAS无法直接将属性作为身份验证的一部分进行检索,因此我们需要建立一个单独的属性存储库实例,一旦用户完全通过身份验证,CAS将与该实例联系。
因此,我们需要使用属性存储库(它具有ldap,jdbc,stub ... https://apereo.github.io/cas/development/configuration/Configuration-Properties.html#stub等许多类型)
我已经为属性存储库配置了jdbc。 (PostgreSQL作为数据库)
首先,您需要添加两个依赖项来build.gradle
compile "org.apereo.cas:cas-server-support-jdbc:${casServerVersion}"
compile "org.apereo.cas:cas-server-support-jdbc-drivers:${casServerVersion}"
然后,创建要在其中获取属性的数据库。例如,名为my_roles
id (serial) | user_name (varchar(50)) | role_name (text[])
----------------------------------------------------------
1 | dg | {'ROLE_READ', 'ROLE_WRITE'}
然后,像这样配置属性存储库
cas.authn.attribute-repository.jdbc[0].sql=SELECT * FROM my_roles WHERE {0}
cas.authn.attribute-repository.jdbc[0].username=user_name
cas.authn.attribute-repository.jdbc[0].user=postgres
cas.authn.attribute-repository.jdbc[0].password=postgres
cas.authn.attribute-repository.jdbc[0].url=jdbc:postgresql://localhost:5432/customer
cas.authn.attribute-repository.jdbc[0].driverClass=org.postgresql.Driver
cas.authn.attribute-repository.jdbc[0].dialect=org.hibernate.dialect.PostgreSQL95Dialect
最后,不要忘记将发布策略添加到您的服务注册表中。
{
...
"attributeReleasePolicy" : {
"@class" : "org.apereo.cas.services.ReturnAllowedAttributeReleasePolicy",
"allowedAttributes" : [ "java.util.ArrayList", [ "role_name" ] ]
}
}
所以,这是结果;
{
"sub": "dg",
...
"role_name":
[
"ROLE_WRITE",
"ROLE_READ"
],
"aud": "http://localhost:8085/login/oauth2/code/login-client",
"grant_type": "AUTHORIZATION_CODE",
...
}