对于一个项目,我制作了一个Spring Boot授权服务器和一个资源服务器。我已经实现了oauth2密码流程。我还创建了一个有角度的Web应用程序,该应用程序将使用资源服务器端点的数据。资源服务器通过使用授权服务器检查令牌。
我想知道登录后传达用户信息的最佳方法。我需要诸如角色/用户ID之类的信息来显示其他页面,隐藏某些功能或使用接收到的令牌从资源服务器收集用户特定的数据
我制作了一个CustomTokenEnhancer,可以向我的令牌响应中添加其他信息。
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
final Map<String, Object> additionalInfo = new HashMap<>();
User user = (User) authentication.getPrincipal();
additionalInfo.put("id", user.getId());
additionalInfo.put("username", authentication.getName());
additionalInfo.put("organization", user.getOrganization());
additionalInfo.put("roles", user.getRoles());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}
这是一个请求令牌后响应的示例。
{
"access_token": "233fda99-3ff7-4766-bfa3-3b211280c64f",
"token_type": "bearer",
"refresh_token": "286e7324-9b8a-46de-a0c7-45e21be552d4",
"expires_in": 35999,
"scope": "read write",
"organization": "organization",
"roles": [
{
"id": "1",
"createdAt": null,
"name": "ROLE_admin",
"permissions": [
{
"id": "1",
"createdAt": null,
"name": "create_profile"
},
{
"id": "2",
"createdAt": null,
"name": "read_profile"
},
{
"id": "3",
"createdAt": null,
"name": "update_profile"
},
{
"id": "4",
"createdAt": null,
"name": "delete_profile"
}
]
}
],
"id": 1,
"username": "test"
}
是否可以安全地存储诸如本地存储中的角色之类的信息,并使用它来确定要隐藏/显示我的Web应用程序的哪些元素?
答案 0 :(得分:0)
这主要取决于您所说的“元素”。
从您的信息位于前端开始,您的用户就可以访问它,因此他可以对其进行修改(无论您将其存储在本地存储中还是其他任何地方)。
认识到这一点,您可以猜测,决定用户访问权限的是后端。
因此,如果您的前端读取您的本地存储以了解是否应显示“编辑”按钮,例如,只要用户使该按钮出现,您的后端就可以验证他有权编辑该内容,那没有问题,但是,如果您要根据此条件隐藏敏感信息,则不是一个好主意,那么您的后端就永远不会发送此信息。
答案 1 :(得分:0)
您必须确定后端的授权。为了保护前端逻辑,您可以使用诸如Jscrambler之类的工具,您可以将其嵌入angular-cli和构建过程中。 Jscrambler使调试代码非常困难。