I cannot authorize my HTTP methods with the token generated by Bearer and Jwt

Asked

Viewed 44 times

-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

1 answer

2

I can’t tell for sure without seeing the call from your method Generatetoken and your request on Postman, there go some considerations that may be trivial but we forget:

1. For an HTTPS request with token authentication is required perform a request for the endpoint that calls your implementation of Generatetoken and thereby get the token for the authenticated user.

Exemplo de request obtendo o token

2. With this token in hand, to all endpoint call decorated with Authorize, the token must be informed in the request of the Postman, in part of Authorization/Bearer Token.

Informando Bearer Token na requisição

3. Make sure you are performing the Postman request with the protocol HTTPS and not HTTP as he had informed above, once dealing with authentication does not make much sense to be HTTP, if you have a method that should not use authentication just memorize it as Allowanonymous or instead of Authorize and maintain HTTPS.

4. Keep in mind that our token is set to expire in 2h, so whenever it expires, a new request to Generatetoken and a new token must be used.

I did a basic project to simulate the issue and it worked correctly, if it is of help, I’m leaving the link here too.

https://github.com/RaphaelX1/Question_511894

Browser other questions tagged

You are not signed in. Login or sign up in order to post.