简体   繁体   中英

Keycloak user roles angular and .net core

i have a Keycloak question. I want to add user roles to my Angular (Client) / .net core (Backend) Application. I have no experience, so I looked at this tutorial: https://medium.com/@xavier.hahn/adding-authorization-to-asp-net-core-app-using-keycloak-c6c96ee0e655

My client send the token to the backend. In the backend I add the [Authorize] attribute to my Controller class. If I send a get to the backend, the authorization process works fine I get the data. But, if I set the [Authorize(Roles = "Administrators")] to the controller method I get a 403 error:

Response {_body: "", status: 403, ok: false, statusText: "Forbidden", headers: Headers, …}
headers: Headers {_headers: Map(5), _normalizedNames: Map(5)}
ok: false
status: 403
statusText: "Forbidden"
type: 2
url: "http://localhost:64336/api/SampleData/authorization"
_body: ""
__proto__: Body

In the access token the user_roles are set:

 "user_roles": [
        "uma_protection",
        "Administrators",
        "Users"
      ],

Does anyone have an idea what's wrong, or does someone know another tutorial?

Many Thanks

Keycloack 4.8.3.

.net core 2.2

Angular 7

you need to verify that your settings are correct.

In the Startup file:

 services.AddAuthorization(options =>
 {
      options.AddPolicy("MyPolice", policy => policy.RequireClaim("myMapper", "MyRole"));
 });

In the Controller file:

[HttpGet]
[Authorize(Policy = "myPolicy")]
public ActionResult Protect()
{
    return Ok("myPolicy work");
}

In the Keycloak, create a role (Clients/Roles/Add Role): Create Role

In the Keycloak, create a mapper (Clients/Mapper/Create): Create Mapper

In the keycloak, create a service account role for you client (Clients/Service Account Roles): Create membership between client and role

Now it should work :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM