0

Estoy Creando una web api con .net core 6, estoy autenticando a traves de Ldap cosa que ya me esta funcionando y hasta se genera el token, realizandolo de la siguiente manera:

[ApiController]
[Route("Usuario")]
public class UsuarioController : ControllerBase
{
    public IConfiguration _configuration;

    public UsuarioController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    [HttpPost]
    [Route("iniciarSesion")]
    public dynamic IniciarSeccion([FromBody] Object optData) 
    {
        string dominio, path;
        dominio = "xxxxx.com.mx";
        path = "LDAP://xxxxx/DC=xxxx,DC=com,DC=mx";

        var data = JsonConvert.DeserializeObject<dynamic>(optData.ToString());

        string user = data.User.ToString();
        string password = data.Password.ToString();

        string domainAndUsername = dominio + @"\" + user;
        DirectoryEntry entry = new DirectoryEntry(path, domainAndUsername, password);
        DirectorySearcher search = new DirectorySearcher(entry);
        DirectorySearcher prueba = new DirectorySearcher(entry);
        search.Filter = "(| (department=TI) (department=COMPRAS) (department=CONTABILIDAD) (department=VENTAS))";
        SearchResult result = search.FindOne();
        prueba.Filter = "(sAMAccountName=" + user + ")";
        prueba.PropertiesToLoad.Add("department");
        prueba.PropertiesToLoad.Add("cn");
        prueba.PropertiesToLoad.Add("mail");
        prueba.PropertiesToLoad.Add("mobile");
        prueba.PropertiesToLoad.Add("employeeNumber");
        prueba.PropertiesToLoad.Add("telephoneNumber");
        prueba.PropertiesToLoad.Add("uidNumber");
        SearchResultCollection? iResult = prueba.FindAll();

        if (result != null)
        {
            var jwt = _configuration.GetSection("Jwt").Get<Jwt>();

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, jwt.Subject),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Key));
            var singIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);

            var token = new JwtSecurityToken(
                jwt.Issuer,
                jwt.Audience,
                claims,
                expires: DateTime.UtcNow.AddDays(7),
                signingCredentials:  singIn
                );

            return new
            {
                success = true,
                message = "Logeado",
                ldapResult = iResult,
                result = new JwtSecurityTokenHandler().WriteToken(token)
            };
        }
        else
        {
            return NotFound();
        }

    }

Hasta ahi todo va bien ya que al revisarlo en postmat en la variable result va el token, empece con la validación para las demás peticiones y agregue esto a la clase Jwt, para poder validar los tokens que hagan la petición, originalmente solo estaban las propiedades:

    public string Key { get; set; }
    public string Issuer { get; set; }
    public string Audience { get; set; }
    public string Subject { get; set; }

    public static dynamic validarToken(ClaimsIdentity identity)
    {
        try
        {
            if(identity.Claims.Count() == 0)
            {
                return new
                {
                    success = false,
                    message = "Verifica si estas enviando un token valido!",
                    result = ""
                };
            }
            else
            {
                return new
                {
                    success = true,
                    message = "Valido",
                    result = ""
                };
            }

        }
        catch (Exception ex)
        {
            return new
            {
                success = false,
                message = "Catch : " + ex.Message,
                result = ""
            };
        }
    }

En la petición que empece a probar, empezo a retornar:

{
    "success": false,
    "message": "Catch : Object reference not set to an instance of an object.",
    "result": ""
}

Justamente da error en la linea

 if(identity.Claims.Count() == 0)

La descripcion dice:

introducir la descripción de la imagen aquí

La petición que hago es la siguiente:

    [HttpGet]
    [Route("listaClientes")]
    public dynamic listaClientes()
    {
        var identity = HttpContext.User.Identities as ClaimsIdentity;
        var rToken = Jwt.validarToken(identity);

        if (!rToken.success)  return rToken; 
        
        
        using (CotizadorContext bd = _context)
        {
            List<Cliente> Lista = (from c in bd.Clientes
                                   select new Cliente
                                   {
                                       NombreCliente = c.NombreCliente,
                                   }).ToList();
            return Lista;
        }
        
        
    }

Todo esto a pesar de probar sin mandar el token con authorization : Bearer ......, al igual que si lo hago sin agregar el token

Actualización

Al modificar en la consulta agregando [Authorize] este en postmant me regresa el siguiente mensaje:

System.InvalidOperationException: Endpoint CotizadorWebV1.Controllers.ClienteController.listaClientes (CotizadorWebV1) contains authorization metadata, but a middleware was not found that supports authorization.

Program.cs

using CotizadorWebV1.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<CotizadorContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("ConexionBD"));
});

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        ValidIssuer = builder.Configuration["Jwt:Issuer"],
        ValidAudience = builder.Configuration["Jwt:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
    };
}); 

var app = builder.Build();



// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

//Agregado
app.UseAuthentication();

app.UseStaticFiles();
app.UseRouting();


app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");

app.MapFallbackToFile("index.html"); ;

app.Run();

Si tengo así el código, marca error de referencia:

if(identity.Claims.Count() == 0)
                {
                    return new
                    {
                        success = false,
                        message = "Verifica si estas enviando un token valido!",
                        result = ""
                    };
                }

Pero si agrego la clave, no manda error:

if("Password_De_Prueba".Count() == 0)
                {
                    return new
                    {
                        success = false,
                        message = "Verifica si estas enviando un token valido!",
                        result = ""
                    };
                }
9

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.