Problems implementing JWT authentication with NET Core 5

Asked

Viewed 12 times

0

Hello, I’m having trouble implementing JWT in my API, I researched and looked at several tutorials on the subject and noticed that they use Identity, but I use Dapper to be able to check if the user exists in the Database and after I Gero the token with the name and email. My problem (I think) it’s time to send the token, because I always have the 401 return and can’t find anything wrong.

I have already tried to pass the Token in the Auth tab of Insomnia as pointed by the print mouse. I have already tried to pass in the Header as well as the print. so far I have not had success, I will put my codes below. I thank you for the help.

Token na aba de autenticação

Token na aba de Header

public class Startup {

  // Properties
  public IConfiguration Configuration { get; }

  // Constructor
  public Startup(IConfiguration configuration) {
    this.Configuration = configuration;
  }

  // This method gets called by the runtime. Use this method to add services to the container.
  public void ConfigureServices(IServiceCollection services) {
    services.AddCors();
    services.AddControllers();

    var jwtToken = new JwtToken();
    this.Configuration.GetSection("JwtToken").Bind(jwtToken);
    var key = Encoding.ASCII.GetBytes(jwtToken.key);
  
    services.AddAuthentication(x => {
      x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
      x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    }).AddJwtBearer(x => {
      // x.RequireHttpsMetadata = false;
      x.SaveToken = true;
      x.TokenValidationParameters = new TokenValidationParameters {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidAudiences = jwtToken.audiences,
        ValidIssuers = jwtToken.issuers,
        ValidateIssuerSigningKey = true,
        RequireExpirationTime = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
      };
    });

    services.AddSingleton<IConfiguration>(Configuration);
    services.AddMapperBLL();
  }

  // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {

    if (env.IsDevelopment()) {
      app.UseDeveloperExceptionPage();
      app.UseSwagger();
    }

    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

    app.UseEndpoints(endpoints => {
      endpoints.MapControllers();
    });
  }

Class that generates the Token and is called in the controller.

public static class TokenService {
  public static UserResponse GenerateToken(this UserResponse infoUser, JwtToken jwtToken) {
    var tokenHandler = new JwtSecurityTokenHandler();
    var dtExpires = DateTime.UtcNow.AddMinutes(decimal.ToDouble(jwtToken.expireMinutes));
    var key = Encoding.ASCII.GetBytes(jwtToken.key); 

    var tokenDescriptor = new SecurityTokenDescriptor {
      Subject = new ClaimsIdentity(new Claim[] {
        new Claim(ClaimTypes.Name, infoUser.nmUser),
        new Claim(ClaimTypes.Email, infoUser.email)
        // new Claim(ClaimTypes.Role, "user.Role.ToString()")
      }),
      Expires = dtExpires,
      SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512)
    };

    var token = tokenHandler.CreateToken(tokenDescriptor);

    infoUser.dtExpire = dtExpires;
    infoUser.token = tokenHandler.WriteToken(token);

    return infoUser;
  }
}

1 answer

0

Hello, after a few more debugs and a good night’s sleep, I managed to figure out the problem. I realized that in token generation I was not passing the information of Issuer and Audience but was validating the information in the class startup. If anyone has any further comments on my code, feel free to comment that I’ll see if it fits my situation.

Thank you.

Browser other questions tagged

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