Skip to content
This repository has been archived by the owner on May 17, 2024. It is now read-only.

Authorization mechanism

Michał B edited this page Jul 21, 2018 · 2 revisions

Json Web Token

This mechanism uses JWT (Json Web Token) to authorize user in WebApi. Every token consists of:

  • User id
  • User role
  • The date before token isn't valid
  • Expiration time
  • The date token was issued
  • URI address of the issuer

Token is created in the JwtHandler.cs service by the method:

public async Task<string> CreateTokenAsync(int userId, string role)

Then this token is used by login action in authorization controller.


Roles

Roles are configured in the Startup.cs class:

public void ConfigureServices(IServiceCollection services)
{
   //...

   services.AddAuthorization(x => x.AddPolicy("admin", p => p.RequireRole("admin")));
   services.AddAuthorization(x => x.AddPolicy("user", p => p.RequireRole("user")));

   //...
}

Roles are used to manage user permissions for controller actions. For example:

[Authorize(Roles = "admin")]
public async Task<IActionResult> GetAdminAsync()

Allows only admins to use this action.

The role is taken from the JWT token.

Clone this wiki locally