Home > Enterprise >  How to perform role based authorization without identity framework?
How to perform role based authorization without identity framework?

Time:07-08

I am looking at a web api which performs authentication/authorization without the identity framework.

The program.cs file has got the authentication configured as follows:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options => ....

The login controller action sets a JWT token with the user's login name and returns it to the caller. Every other controller action has either the [Authorize] or [AllowAnonymous] attribute to control access.

I am tasked to add role based authorization to this web api. For example so that I can use [Authorize(Roles = "Administrator")] for admin controller actions. In the database user table I have created the Role column as a placeholder for the user's role; thus performing role based authorization.

I am looking at this link: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-6.0 - but this is about role based authorization when using identity. But I am not using identity framework.

A solution I am thinking is - during login, write the role into the JWT token and then code an attribute for each role (which is to be applied to respective controller actions) such that it compares the role in the JWT token.

Is role based authorization dependent on .net identity? Or can I simply set the value of Role or Claim into the JWT token (during login) and via the usual [Authorize(Roles = "Administrator")] automatically perform role based authorization, is this supported? Any simple example or reference on this will be helpful.

CodePudding user response:

Correct me if I understand your question wrong, but do you want to implement a custom provider to authenticate via your API?

Here I've implemented a custom provider that validates user/pass with data stored in Ontraport web service.

https://github.com/mysteryx93/OntraportApi.NET/tree/master/OntraportApi.IdentityCore

CodePudding user response:

when you generate the token ,add the "role"claim

var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, "Jeffcky"),
                new Claim(ClaimTypes.Role,"Administrator")
            };
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("........"));

            var token = new JwtSecurityToken(
              issuer: "......",
              audience: "......",
              claims: claims,
              notBefore: DateTime.Now,
              expires: DateTime.Now.AddMinutes(5),
              signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
            );
var token=new JwtSecurityTokenHandler().WriteToken(token);
  • Related