Search code examples
c#asp.net-coreasp.net-identitybearer-token

ASP.NET Core 3 with Angular 8, ASP.NET Core Identity, Roles and token based authentication


Problem:
Creating a WebApi that is secured with a token passed from api client.
Some api methods should be available only to users with certain roles defined.
E.g.

The scenario would look like this:
Angular8 calls WebApi to login

httpClient.Post(new LogInRequest(userName, password));

WebApi signs in the user and generates token

signInManager.PasswordSignInAsync(userName, password);
var token = GenerateToken(userName); // token should be generated internally
return token;

Angular8 calls WebApi and includes in header the token

httpClient.Post(header: "TOKEN", new CreateCompanyRequest(company));

Now the WebApi checks if the user assigned to token is allowed to perform this action

[Authorize("Supervisor")] // only user with Supervisor role should be able to use this controller
public class CompanyController : Controller

Above code is just a sample how I would see it working. So far I've tried reading some JWT Bearer explanation but most of these articles were from old version of asp.net. If you could explain to me how this authentication should work, or point me to some documentation on how to combine asp.net core identity with webapi token authentication


Solution

  • You could refer to below link which introduce to you a complete sample to use asp.net core Identity authentication ,JWT token authorization in asp.net core web api:

    https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login

    You could just adapt its source code to asp.net core 3.0 with 3.0 packages and it will work.