How to retrieve KeyCloak resource based permission value in C# asp.net core Identity Claims

How to retrieve KeyCloak resource based permission value in C# asp.net core Identity Claims

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text.Json;

//Ressource/Client Roles
public static IList<string> GetRessourceAccessRoles(ClaimsPrincipal claimsPrincipal, string resourceName)
{
	using (JsonDocument jd = JsonDocument.Parse(claimsPrincipal.Claims.FirstOrDefault(c => c.Type == "resource_access").Value))
	{
		return JsonSerializer.Deserialize<List<string>>(jd.RootElement.GetProperty(resourceName).GetProperty("roles").GetRawText());
	}
}

//Realm Roles
public static IList<string> GetRealmAccessRoles(ClaimsPrincipal claimsPrincipal)
{
	using (JsonDocument jd = JsonDocument.Parse(claimsPrincipal.Claims.FirstOrDefault(c => c.Type == "realm_access").Value))
	{
		return JsonSerializer.Deserialize<List<string>>(jd.RootElement.GetProperty("roles").GetRawText());
	}
}

error handling omitted…

Thank you for your prompt reply mbonn

Matthias Bonn, actually I am able to access roles, but I want to access resource scopes and Permissions and policy value in C# .net core Identity Claims so can you please provide 1 sample for the same.Thanks**

Sorry I can not provide a sample, I never used KC’s authorization services, I try to do authorization in the client, whenever possible. You could use the developer tools of your web browser to find aut what API calls are done by the admin console to access them. Or you could look into the code of the official KC Java adapters, try to find out what they are doing, and translate it to C#…

Yea don’t provide a sample Mr. mbonn
but is there any way there, to retrieve the scopes permissions and policy from keycloak inside identity claim using access token from keycloak
which is the best approach to make authorization dynamic using keycloak so that we can do changes inside keycloak rather than inside c# code for dynamic updates of permissions and (roles) etc.

You could use the role or group features of keycloak. Add roles to you users or put them into apropriate groups, add a group membership mapper to yout client and then evaluate the group membership claims in the C# application… So to change the permission of a user, change their group membership in KC…