英文:
Bearer error="invalid_token", error_description="The signature key was not found" NET Core 7
问题
I'm starting a webApi project for a college assignment and I'm trying to do the authorization while using JWT Tokens, this is my current config:
This is my "UsuariosController.cs" file:
[HttpPost("login", Name = "LoginUsuario")]
public async Task<ActionResult<Usuario>> LoginUsuario(Usuario Usuario)
{
var usuarioEncontrado = await _context.Usuarios.FirstOrDefaultAsync(
u => u.Correo == Usuario.Correo
);
if (!BCrypt.Net.BCrypt.Verify(Usuario.Contrasena, usuarioEncontrado.Contrasena))
{
return BadRequest("Contraseña incorrecta");
}
if (usuarioEncontrado == null)
{
return NotFound();
}
string token = GenerarToken(usuarioEncontrado);
return Ok(token);
}
private string GenerarToken(Usuario usuario)
{
List<Claim> claims = new List<Claim> { new Claim(ClaimTypes.Email, usuario.Correo) };
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value!)
);
var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: cred
);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
return jwt;
}
This is my "program.cs" file:
using Backend.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using System.Text;
using Swashbuckle.AspNetCore.Filters;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DataContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition(
"oauth2",
new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
}
);
options.OperationFilter<SecurityRequirementsOperationFilter>();
});
//JWT Authentication
builder.Services.AddAuthentication("Bearer").AddJwtBearer();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
// app.UseAuthentication();
app.MapControllers();
app.Run();
And the appsettings.json file where my secret key to generate the token is located:
{
"AppSettings": {
"Token": "*G-JaNdRgUkXp2s5v8y/B?E(H+MbPeSh"
},
"ConnectionStrings": {
"DefaultConnection": ""
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Any idea of what I'm missing on?
I'm getting a Bearer error="invalid_token", error_description="The signature key was not found" while passing the JWT token on Postman to access the HTTP method that has the authorize property on it:
[Authorize]
[HttpGet("listaUsuarios", Name = "GetUsuarios")]
public async Task<ActionResult<IEnumerable<Usuario>>> GetUsuarios()
{
return await _context.Usuarios.ToListAsync();
}
英文:
i'm starting a webApi project for a college assignment and I'm trying to do the authorization while using JWT Tokens, this is my current config:
This is my "UsuariosController.cs" file
[HttpPost("login", Name = "LoginUsuario")]
public async Task<ActionResult<Usuario>> LoginUsuario(Usuario Usuario)
{
var usuarioEncontrado = await _context.Usuarios.FirstOrDefaultAsync(
u => u.Correo == Usuario.Correo
);
if (!BCrypt.Net.BCrypt.Verify(Usuario.Contrasena, usuarioEncontrado.Contrasena))
{
return BadRequest("Contraseña incorrecta");
}
if (usuarioEncontrado == null)
{
return NotFound();
}
string token = GenerarToken(usuarioEncontrado);
return Ok(token);
}
private string GenerarToken(Usuario usuario)
{
List<Claim> claims = new List<Claim> { new Claim(ClaimTypes.Email, usuario.Correo) };
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_configuration.GetSection("AppSettings:Token").Value!)
);
var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var token = new JwtSecurityToken(
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: cred
);
var jwt = new JwtSecurityTokenHandler().WriteToken(token);
return jwt;
}
This is my program.cs file:
using Backend.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Swagger;
using System.Text;
using Swashbuckle.AspNetCore.Filters;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<DataContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition(
"oauth2",
new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
}
);
options.OperationFilter<SecurityRequirementsOperationFilter>();
});
//JWT Authentication
builder.Services.AddAuthentication("Bearer").AddJwtBearer();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
// app.UseAuthentication();
app.MapControllers();
app.Run();
And the appsettings.json file where my secret key to generate the token is located:
{
"AppSettings": {
"Token": "*G-JaNdRgUkXp2s5v8y/B?E(H+MbPeSh"
},
"ConnectionStrings": {
"DefaultConnection": ""
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Any idea of what I'm missing on?
I'm getting a Bearer error="invalid_token", error_description="The signature key was not found" while passing the JWT token on Postman to access the HTTP method that has the authorize property on it:
[Authorize]
[HttpGet("listaUsuarios", Name = "GetUsuarios")]
public async Task<ActionResult<IEnumerable<Usuario>>> GetUsuarios()
{
return await _context.Usuarios.ToListAsync();
}
答案1
得分: 0
以下是JWT身份验证的代码部分的中文翻译:
// 添加JWT身份验证
builder.Services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.RequireHttpsMetadata = false;
var key = Encoding.UTF8.GetBytes(builder.Configuration["AppSettings:Token"]);
o.SaveToken = true;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
...
app.UseAuthentication();
app.UseAuthorization();
请注意,这只是代码的翻译部分,不包括注释或其他内容。
英文:
You can refer to the below code to define JWT Authentication:
// ADD JWT Authentication
builder.Services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.RequireHttpsMetadata = false;
var key = Encoding.UTF8.GetBytes(builder.Configuration["AppSettings:Token"]);
o.SaveToken = true;
o.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(key)
};
});
...
app.UseAuthentication();
app.UseAuthorization();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论