I follow the tutorial link below.
I am trying to understand how it works and I want to use role-based authentication using this token. so I made another policy in the Startup.cs
file as below.
And I tried to use it like [Authorize(Policy = "admin")]
or [Authorize(Policy = "ApiUser")]
in the controller but every time I try I get unauthenticated
using postman
.
What am I missing? how to make roles-based authentication based on the tutorial?
Startup
services.AddAuthorization(options =>
{
options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
});
services.AddAuthorization(options =>
options.AddPolicy("admin", policy => policy.RequireRole("admin"))
);
Auth Controller
// POST api/auth/login
[HttpPost("login")]
public async Task<IActionResult> Post([FromBody]CredentialsViewModel credentials)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var identity = await GetClaimsIdentity(credentials.UserName, credentials.Password);
if (identity == null)
{
//return null;
return BadRequest(Error.AddErrorToModelState("login_failure", "Invalid username or password.", ModelState));
}
var id = identity.Claims.Single(c => c.Type == "id").Value;
var user = await _userManager.FindByIdAsync(id);
IList<string> role = await _userManager.GetRolesAsync(user);
var jwt = await Tokens.GenerateJwt(identity, role[0], _jwtFactory, credentials.UserName, _jwtOptions, new JsonSerializerSettings { Formatting = Formatting.Indented });
return new OkObjectResult(jwt);
}
I tried with all method and none of them working
[Authorize(Policy = "ApiUser")]
[HttpGet("getPolicy")]
public string GetPolicy()
{
return "policyWorking";
}
[Authorize(Roles = "admin")]
[HttpGet("getAdmin")]
public string GetAdmin()
{
return "adminWorking";
}
[Authorize ]
[HttpGet("getAuthorize")]
public string GetAuthorize()
{
return "normal authorize Working";
}
2
Answers
I’ve made mine using this tutorial.
It also works with .Net Core 3.1.
@Update
I’m using policies for that:
And in Controller
and in creating JWT Token:
Firstly,be sure you have add json string in your
appsettings.json
otherwise you would always get401 unauthorized
:1.If you want to use the following way to register the service:
The authorize attribute should be like below:
2.If you want to use the following way:
You need to remove the service from Startup.cs:
Then,don’t forget to add claim with role in
JwtFactory.GenerateEncodedToken
like below: