Problem damit, JWT -Token in Zwiebelarchitektur zu interpretierenC#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Problem damit, JWT -Token in Zwiebelarchitektur zu interpretieren

Post by Anonymous »

Code: Select all

MyAPI.Core.Microservice.API/Program.cs
:

Code: Select all

// ...
builder.Services.AddControllers()
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressModelStateInvalidFilter = true;
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddInfrastructureSwagger();

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = configuration["Jwt:Issuer"], // Correspondente ao issuer
ValidAudience = configuration["Jwt:Audience"], // Correspondente à audience
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]!))
};

// Adicionando logs de erro para melhor depuração
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
Console.WriteLine($"Authentication failed: {context.Exception.Message}");
Console.WriteLine($"Token recebido: {context.Request.Headers["Authorization"]}");
return Task.CompletedTask;
}
};
});
// ...
< /code>
MyAPI.Core.Microservice.API/Contollers/TokenController.cs
:

Code: Select all

namespace MyAPI.Core.Microservice.API.Controllers;
using MyAPI.Core.Microservice.Domain.Models.Entities;
using Microsoft.Extensions.Configuration;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Mvc;
using System.Text;
using Microsoft.Extensions.Logging;

/// 
/// Controlador responsável pela gestão do token de autenticação.
/// 
[ApiController]
[Route("api/auth-token")]
public class TokenController : ControllerBase
{
private readonly string chaveSecreta;
private readonly string issuer;
private readonly string audience;
private readonly string AdmUsername;
private readonly string AdmPassword;
private readonly ILogger _logger;

/// 
/// Construtor do TokenController.
/// 
/// 
Configurações da aplicação, contendo as informações de JWT e credenciais de administrador.
/// Logger para registrar eventos e erros.
/// Lançado quando as configurações de JWT ou administrador estão ausentes.
public TokenController(IConfiguration configuration, ILogger logger)
{
issuer = configuration["Jwt:Issuer"]!;
audience = configuration["Jwt:Audience"]!;
chaveSecreta = configuration["Jwt:Key"]!;
AdmUsername = configuration["Adm:Username"]!;
AdmPassword = configuration["Adm:Password"]!;
_logger = logger;
}

/// 
/// Criar um novo token
/// 
/// Objeto contendo as credenciais do administrador
/// Token JWT gerado
[HttpPost]
[ProducesResponseType(typeof(string), 201)]  // Sucesso na criação do token: 200 Good Request
[ProducesResponseType(typeof(object), 400)]  // Erro de validação: 400 Bad Request
[ProducesResponseType(typeof(object), 500)]  // Erro do servidor: 500 Internal Server Error
public ActionResult GetToken(AdmUser admUser)
{
if(
admUser.Username == AdmUsername &&
admUser.Password == AdmPassword)
{
var tokenJwt = GerarTokenJwt(admUser.Username);
return Ok(tokenJwt);
}
_logger.LogWarning("Administrative credentials incorrect for user: {Username}", admUser.Username);
return BadRequest("Administrative credentials incorrect.");
}

private string GerarTokenJwt(string username)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(chaveSecreta));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new System.Security.Claims.Claim[]
{
new System.Security.Claims.Claim("username", username),
};

var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
< /code>
MyAPI.Core.Microservice.API.Client/DependencyInjection/DependencyInjectionSwagger.cs
:

Code: Select all

namespace MyAPI.Core.Microservice.API.Controllers;
using MyAPI.Core.Microservice.Domain.Models.Entities;
using Microsoft.Extensions.Configuration;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Mvc;
using System.Text;
using Microsoft.Extensions.Logging;

/// 
/// Controlador responsável pela gestão do token de autenticação.
/// 
[ApiController]
[Route("api/auth-token")]
public class TokenController : ControllerBase
{
private readonly string chaveSecreta;
private readonly string issuer;
private readonly string audience;
private readonly string AdmUsername;
private readonly string AdmPassword;
private readonly ILogger _logger;

/// 
/// Construtor do TokenController.
/// 
/// 
Configurações da aplicação, contendo as informações de JWT e credenciais de administrador.
/// Logger para registrar eventos e erros.
/// Lançado quando as configurações de JWT ou administrador estão ausentes.
public TokenController(IConfiguration configuration, ILogger logger)
{
issuer = configuration["Jwt:Issuer"]!;
audience = configuration["Jwt:Audience"]!;
chaveSecreta = configuration["Jwt:Key"]!;
AdmUsername = configuration["Adm:Username"]!;
AdmPassword = configuration["Adm:Password"]!;
_logger = logger;
}

/// 
/// Criar um novo token
/// 
/// Objeto contendo as credenciais do administrador
/// Token JWT gerado
[HttpPost]
[ProducesResponseType(typeof(string), 201)]  // Sucesso na criação do token: 200 Good Request
[ProducesResponseType(typeof(object), 400)]  // Erro de validação: 400 Bad Request
[ProducesResponseType(typeof(object), 500)]  // Erro do servidor: 500 Internal Server Error
public ActionResult GetToken(AdmUser admUser)
{
if(
admUser.Username == AdmUsername &&
admUser.Password == AdmPassword)
{
var tokenJwt = GerarTokenJwt(admUser.Username);
return Ok(tokenJwt);
}
_logger.LogWarning("Administrative credentials incorrect for user: {Username}", admUser.Username);
return BadRequest("Administrative credentials incorrect.");
}

private string GerarTokenJwt(string username)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(chaveSecreta));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new System.Security.Claims.Claim[]
{
new System.Security.Claims.Claim("username", username),
};

var token = new JwtSecurityToken(
issuer: issuer,
audience: audience,
claims: claims,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: credentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
< /code>
Errors:

Authentication failed: IDX14100: JWT is not well formed, there are no dots (.).

The token needs to be in JWS or JWE Compact Serialization Format. (JWS): 'EncodedHeader.EndcodedPayload.EncodedSignature'. (JWE): 'EncodedProtectedHeader.EncodedEncryptedKey.EncodedInitializationVector.EncodedCiphertext.EncodedAuthenticationTag'.

Token recebido: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluQHdhcnJlbi5kb21haW4uY29tIiwiZXhwIjoxNzQwNjA1MjkzLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjUwMDAifQ.gZXRCeAbphb-WTqu3g3KQFjVyqJPULH31hRreQxnYpk

I've been trying this for days and haven't gotten any results. The funny thing is that following single shot architectures where the dependency file is in the same directory as program.cs
funktioniert es perfekt. Es ist wirklich eine sehr komplexe Herausforderung oder etwas, das ich einfach nicht sehen kann.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post