Bearer error="invalid_token", error_description="The signature key was not found" NET Core 7

huangapple go评论53阅读模式
英文:

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(&quot;login&quot;, Name = &quot;LoginUsuario&quot;)]
    public async Task&lt;ActionResult&lt;Usuario&gt;&gt; LoginUsuario(Usuario Usuario)
    {
        var usuarioEncontrado = await _context.Usuarios.FirstOrDefaultAsync(
            u =&gt; u.Correo == Usuario.Correo
        );

        if (!BCrypt.Net.BCrypt.Verify(Usuario.Contrasena, usuarioEncontrado.Contrasena))
        {
            return BadRequest(&quot;Contrase&#241;a incorrecta&quot;);
        }

        if (usuarioEncontrado == null)
        {
            return NotFound();
        }
        string token = GenerarToken(usuarioEncontrado);
        return Ok(token);
    }

    private string GenerarToken(Usuario usuario)
    {
        List&lt;Claim&gt; claims = new List&lt;Claim&gt; { new Claim(ClaimTypes.Email, usuario.Correo) };
        var key = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(_configuration.GetSection(&quot;AppSettings:Token&quot;).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(&quot;DefaultConnection&quot;);
builder.Services.AddDbContext&lt;DataContext&gt;(options =&gt; options.UseSqlServer(connectionString));

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen(options =&gt;
{
    options.AddSecurityDefinition(
        &quot;oauth2&quot;,
        new OpenApiSecurityScheme
        {
            In = ParameterLocation.Header,
            Name = &quot;Authorization&quot;,
            Type = SecuritySchemeType.ApiKey,
        }
    );

    options.OperationFilter&lt;SecurityRequirementsOperationFilter&gt;();
});

//JWT Authentication
builder.Services.AddAuthentication(&quot;Bearer&quot;).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:

{
  &quot;AppSettings&quot;: {
    &quot;Token&quot;: &quot;*G-JaNdRgUkXp2s5v8y/B?E(H+MbPeSh&quot;
  },
  &quot;ConnectionStrings&quot;: {
    &quot;DefaultConnection&quot;: &quot;&quot;
  },
  &quot;Logging&quot;: {
    &quot;LogLevel&quot;: {
      &quot;Default&quot;: &quot;Information&quot;,
      &quot;Microsoft.AspNetCore&quot;: &quot;Warning&quot;
    }
  },
  &quot;AllowedHosts&quot;: &quot;*&quot;
}

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(&quot;listaUsuarios&quot;, Name = &quot;GetUsuarios&quot;)]
        public async Task&lt;ActionResult&lt;IEnumerable&lt;Usuario&gt;&gt;&gt; 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 =&gt;
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =&gt;
{
    o.RequireHttpsMetadata = false;              
    var key = Encoding.UTF8.GetBytes(builder.Configuration[&quot;AppSettings:Token&quot;]);
    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();

huangapple
  • 本文由 发表于 2023年4月17日 09:38:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031189.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定