Andreas Sjöberg
Andreas Sjöberg

Reputation: 42

Add Authorization to AspNet Core 3.0-preview React project (with Authentication)

Creating a new aspnet core project using dotnet new react --name myproject --auth Individual sets up a new React project with IdentityServer4 and authentication.

I want to add authorization (roles, policies, claims), so that I can decorate methods like:

[HttpGet]
[Authorize(Roles = "Administrator")]    <-- LIKE THIS
public IEnumerable<WeatherForecast> Get()
{
    ...
}

I've managed to do this in a project without IdentityServer, and I've Googled around for many hours without success.

What steps do I need to add to the template project to add authorization?

Thanks in advance!

I've tried experimenting with adding different stuff to Startup.cs, like:

services.AddRoles<IdentityRole>();
// ... or ...
services.AddAuthorization(...);
$ dotnet --version
3.0.100-preview7-012821

Upvotes: 0

Views: 708

Answers (1)

Venkata K. C. Tata
Venkata K. C. Tata

Reputation: 5547

I will try to add as much as info possible hoping that you are using identity server 4 and implicit flow on the react front end and API has your identity server as the authority.

You need one client and one API resource on the Identity Server. 1. Implicit flow for your react front end. 2. You API need to be added as an api resource.

The implicit flow client should have access to the scope of api client.

Follow steps from https://github.com/IdentityServer/IdentityServer4.AccessTokenValidation

The user needs to have an Administrator role. You can add it as a role directly in the user roles table in the database or search for profile service for identity server on google and in GetProfileDataAsync(ProfileDataRequestContext context) method check if the user id and add the administrator role as a role claim to issued claims list.

context.IssuedClaims.Add(roleClaim); once this is done, now the token that react client receives has a role claim which says it has administrator role and on calls to api, the api will know the role exists.

Upvotes: 1

Related Questions