no funciona el bearer

This commit is contained in:
2026-09-09 14:06:28 +02:00
parent c5494f60e6
commit f9e184c383
8 changed files with 672 additions and 115 deletions

View File

@@ -1,128 +1,104 @@
using bdCOAS.db;
using Microsoft.AspNetCore.Mvc;
using SwaggerAutenticacion.Clases;
using System.Linq.Dynamic.Core;
using tsUtilidades;
using System.IdentityModel.Tokens.Jwt;
using System.Net;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using bdEmtusa;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using SwaggerAutenticacion.Clases;
namespace SwaggerAutenticacion.Controllers
namespace SwaggerAntifraude.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Route("[controller]")]
public class AuthController : Controller
public class AuthController : ControllerBase
{
private readonly IConfiguration jwtSettings;
private readonly IConfiguration _configuration;
public AuthController(IConfiguration configuration)
{
jwtSettings = configuration.GetSection("Jwt");
_configuration = configuration;
}
[HttpPost("ComprobarUser")]
public ActionResult<string> PostComprobarUser([FromBody] DatosAuth model)
[AllowAnonymous]
[HttpPost("login")]
public IActionResult Login([FromBody] DatosAuth datos)
{
var bd = bdCOAS.tsCOAS.NuevoContextoDirecto();
if (!ModelState.IsValid)
return BadRequest(ModelState);
var token = AuthenticateUser(datos);
if (token == null)
return Unauthorized("Nombre de usuario o contraseña incorrectos.");
try
if (token.Equals("no autorizado"))
{
autorizacionesexternas externo = bd.autorizacionesexternas.FirstOrDefault(x => x.Codigo == model.nombreExterno);
//var externo = bd.autorizacionesexternas.FirstOrDefault(x => x.Nombre == model.nombreExterno);
if (externo != null)
{
var pwEmpresaEncrypt = tsUtilidades.crypt.SHA1("M3Soft." + model.pwExterno);
if (pwEmpresaEncrypt != externo.HashPassword) throw new Exception("PassWord Incorrecta");
}
else
{
throw new Exception("Autorización no encontrada.");
}
var token = "";
try
{
var sContraseñaenc = tsUtilidades.crypt.SHA1("M3Soft." + model.pwColegiado);
Exception ex = null;
accesoswebcoas nac = null;
var col = bd.Colegiados.First(x => x.NumeroColegiado == model.identificacionColegiado || x.NIF == model.identificacionColegiado);
clavesacceso.LoginCoas(bd, col.NumeroColegiado, sContraseñaenc, "", clavesacceso.TipoLoginEnum.EXTERNOS_1, ref ex, ref nac);
if (ex != null) throw ex;
externo.FechaUltimaConexion = DateTime.Now;
bd.Update(externo);
bd.SaveChanges();
token = AuthHandler.GenerateJwtToken(jwtSettings, col.idColegiado.ToString());
return Ok(new { token });
}
catch (tsExcepcion e)
{
return Unauthorized("Credenciales Colegiado no válidas. " + e.Message);
}
catch (Exception e)
{
return BadRequest($"Ha ocurrido un error. Mensaje de error: {e.Message}");
}
}
catch (Exception e)
{
return Unauthorized("Credenciales Empresa no válidas. " + e.Message);
return Unauthorized("Usuario no autorizado");
}
return Ok(BuildLoginResponse(token));
}
[HttpPost("LoginExterno")]
public ActionResult<object> PostLoginExterno([FromBody] DatosAuthEmail model)
private string GenerateJwtToken(DatosAuth auth)
{
var bd = bdCOAS.tsCOAS.NuevoContextoDirecto();
// string ip = HttpContext.Connection.RemoteIpAddress?.ToString();
try
var jwtSettings = _configuration.GetSection("Jwt");
var key = Encoding.UTF8.GetBytes(jwtSettings["Key"]!);
var claims = new[]
{
var externo = bd.autorizacionesexternas
.FirstOrDefault(x => x.Codigo == model.nombreExterno)
?? throw new Exception("Autorización no encontrada.");
new Claim(JwtRegisteredClaimNames.Sub, auth.nombreExterno),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
//new Claim(ClaimTypes.Role, persona.ADMINISTRARPTYREGISTRO == true ? "Supervisor" : "Lectura")
};
var pwEncrypt = tsUtilidades.crypt.SHA1("M3Soft." + model.pwExterno);
if (pwEncrypt != externo.HashPassword)
throw new Exception("Password Incorrecta.");
// Solo guardamos nombreExterno + tipo en el token
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, model.nombreExterno),
new Claim("AuthType", "EmailOnly")
};
var token = AuthHandler.GenerateJwtToken(jwtSettings, claims);
externo.FechaUltimaConexion = DateTime.Now;
bd.Update(externo);
bd.SaveChanges();
// if (externo.Codigo!="GCOAS") tsUtilidades.TsNotificacionesClient.RegistrarAsync("LoginExterno", "Login Externo " + externo.Nombre + " - IP: " + ip, TsNotificacionesClient.TipoNotificacionEnum.INFO);
return Ok(new { token });
}
catch (Exception e) when (
e.Message.Contains("no encontrada") ||
e.Message.Contains("Incorrecta"))
var tokenDescriptor = new SecurityTokenDescriptor
{
tsUtilidades.TsNotificacionesClient.RegistrarAsync("Credenciales LoginExterno incorrectas", e.Message,TsNotificacionesClient.TipoNotificacionEnum.CRÍTICO);
return Unauthorized("Credenciales Empresa no válidas. " + e.Message);
}
catch (Exception e)
{
tsUtilidades.TsNotificacionesClient.RegistrarAsync("Error en LoginExterno", e.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR);
return BadRequest($"Ha ocurrido un error: {e.Message}");
}
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddMinutes(double.Parse(jwtSettings["ExpiresInMinutes"]!)),
Issuer = jwtSettings["Issuer"],
Audience = jwtSettings["Audience"],
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
private static object BuildLoginResponse( string token)
{
return new
{
Token = token,
//User = new
//{
// persona.NIF,
// persona.NOMBRE,
// persona.APELLIDOS,
// persona.ADMINISTRARPTYREGISTRO
//}
};
}
private string AuthenticateUser(DatosAuth datos)
{
using (var context = tscEmtusa.NuevoContexto(SoloLectura: true))
{
var login = context.configuracion.First(x => x.codigo == "auth.login").valor;
var pass = context.configuracion.First(x => x.codigo == "auth.pass").valor;
if (datos.nombreExterno != "emtusanot" || datos.pwExterno != "tsemt2026#..")
{
return ("Credenciales incorrectas");
}
var jwtToken = GenerateJwtToken(datos);
return jwtToken;
}
}
}
}