gpt4 book ai didi

cas - 如何在 JWT 中包含经过身份验证的用户角色?

转载 作者:行者123 更新时间:2023-12-05 03:52:32 35 4
gpt4 key购买 nike

我已将 CAS 配置为 OAuth2 服务器。登录成功后返回JWT,但是JWT中roles字段一直为空,如;

{
"sub": "dg",
...
"roles": [],
"nonce": "",
"client_id": "first-client",
"credentialType": "UsernamePasswordCredential",
...

}

如何在我登录时获取经过身份验证的用户角色并将其放入 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/ ),

Today, CAS is unable to retrieve attributes as part of authentication directly so we need to set up a separate attribute repository instance that CAS will contact once the user is fully authenticated.

因此,我们需要使用属性存储库(它有多种类型,如 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",
...
}

关于cas - 如何在 JWT 中包含经过身份验证的用户角色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62155196/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com