如何从Keycloak获取用户id和用户UUID/GUID?

Hos*_*lah 3 reactjs keycloak .net-core

我在 docer 中使用 Keycloak 并托管在https://accounts.example.com.

我使用 React 作为我的客户端库,登录后,用户进入https://user.example.com.

此 React 客户端使用位于 .NET Core API https://api.user.example.com。

我用来keycloak.js管理 React 面板中的访问。

现在假设用户想要创建一张票证。我将此票证信息发送到 API:

{
    title: 'Urgent backup',
    priority: 'urgent',
    description: 'Please backup my files immediately'
}
Run Code Online (Sandbox Code Playgroud)

在我们的数据库中,我们有这样的设计:

create table Tickets
(
    Id bigint not null primary identity(1, 1),
    UserGuid uniqueidentifier not null, -- How should I fill this column?
    Title nvarchar(200) not null,
    PriorityId int not null,
    Description nvarchar(max) not null
)
Run Code Online (Sandbox Code Playgroud)

问题是,API 应该从用户那里提取永久数据。

当然,我不能将emailor存储在该列中。username我什至不能依赖usernameoremail因为 Keycloak 的管理面板允许配置此设置:

在此输入图像描述

因此,最好的选择是在 Keycloak 中为用户提供一个GUID或UUID,并在 open id 令牌中检索它。

我搜索过,但找不到如何执行此操作。

你能帮我吗?

sve*_*ben 11

默认情况下,您的访问令牌应该有一个主题 ( sub) 声明,其值为 Keycloak 中用户的 id 值。那是一个UUID。您可以从令牌中提取该 ID 并使用它。

也许 ASP.NET core 会自动执行此操作,并提供主题声明作为您的用户名。