-1
Good night,
I am implementing authentication and authorization in my Web API in Asp.net core 5.0. Yesterday, I had success with some authorizations. However, when I went to try to finish implementing today, I can no longer authorize anyone to use any HTTP method. All result in 401 Unauthorized response.
Below are some prints of my code.
Configureservice method in Startup.Cs.
//Autenticação e Autorização
var key = Encoding.ASCII.GetBytes(GenerateKey.secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x => {
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddAuthorization(opt =>
{
var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme);
defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
opt.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();
});
Configure method in startup.Cs.
app.UseAuthentication();
app.UseAuthorization();
Function of creation of Token
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using MentalizeAPI.Models;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
namespace Mentalize.WebAPI.Authentication
{
public class TokenServicePaciente
{
public static string GenerateToken(Paciente paciente){
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(GenerateKey.secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new System.Security.Claims.ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, paciente.email.ToString()),
new Claim(ClaimTypes.Role, paciente.tipoLogin.ToString())
}),
Expires = DateTime.UtcNow.AddHours(2),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
}
One of my http methods using the authentication engine.
[HttpGet]
[Authorize(Roles = "paciente")]
public async Task<IActionResult> Get([FromQuery]PageParams pageParams)
{
var crencaNuclear = await _repo.GetAllCrencasNuclearesAsync(pageParams, true);
var crencaNuclearResult = _mapper.Map<IEnumerable<CrencaNuclearDto>>(crencaNuclear);
Response.AddPagination(crencaNuclear.CurrentPage, crencaNuclear.PageSize, crencaNuclear.TotalCount, crencaNuclear.TotalPages);
return Ok(crencaNuclearResult);
}
Anyway, I believe that this information is enough for you to understand how I am implementing authorization and authentication. I get the token normally by the Postman. But when using to access an HTTP method, as shown above, passing Key: Authorization, Value: Bearer Token in header. I get Unauthorized. Can someone tell me where I’m going wrong?
I appreciate any help and am willing to send more codes in order to solve the problem.
Thank you!
Add an example request with the token
– Leandro Angelo