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.
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;
}
}