首页 > 解决方案 > Keycloak - WPF 检查权限

问题描述

我有一个 WPF 应用程序(.net 462 和 API .net5.0)。

我已经在 api 上设置了 openid 并且这个工作,权限工作,但是在 WPF 应用程序上我必须检查应用程序元素的权限(菜单访问,按钮访问)。

获取令牌工作,但我不知道如何在 openid 时验证范围

关键时钟配置:

我创建了两个用户“user-test-ok”和“user-test-ko”,“user-test-ok”具有客户端角色“DemoRole”。

我已经测试了用户的内省,以验证用户的范围为“demo:read”,但这不起作用。

我不想使用 keycloak API,我想使用 openid 系统来可能通过其他 OAuth2.0 系统更改 keycloak。

这是我尝试检查授权范围的代码:

var requestUri = new Uri($"https://localhost:8443/auth/realms/{realm}/protocol/openid-connect/token/introspect");

using (var client = new HttpClient())
{
    var req = new HttpRequestMessage(HttpMethod.Post, requestUri);
    req.Headers.Add("cache-control", "no-cache");
    req.Headers.Add("accept", "application/x-www-form-urlencoded");

    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

    req.Content = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        { "token_type_hint", "requesting_party_token" },
        { "token", tokenResult.AccessToken },
        { "client_id", clientId },
        { "client_secret", clientSecret },
        { "scope", "test:read" },
    });

    var response = client.SendAsync(req).Result;

    if (!response.IsSuccessStatusCode)
    {
        throw new Exception();
    }

    var responseString = response.Content.ReadAsStringAsync().Result;

}

你知道怎么做吗?

标签: wpfkeycloakopenid

解决方案


如果我在这里阅读令牌自省端点文档,那么它没有说明将范围 ({ "scope", "test:read" },) 作为参数传递。取而代之的是,您从该请求中获取返回的内容,然后首先检查有效声明是否为真。这表明令牌仍然有效且有效。

然后您只需检查返回的数据。或者您只需使用访问权限或 ID-token 中的范围值来让用户访问应用程序中的功能。

请检查请求在Fiddler之类的工具中返回的内容。


推荐阅读