0

Necesito ayuda con este error de loggin por favor y gracias.

  public class User
    {
        //Properties.

        [Key]       
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Column(TypeName = "int")]  
        public int Id { get; set; }

        [Required(ErrorMessage = "The Name is Required")]
        [MaxLength(20, ErrorMessage ="The Neme Cannot Exceed 20 Characters")]
        public string Name { get; set; }

        [Required(ErrorMessage = "The Last Name is Requiered")]
        [MaxLength(20, ErrorMessage = "The Last Name Cannot Exceed 20 Characters")]
        public string LastName { get; set; }

        [Required(ErrorMessage = "The Age is Requiered")]        
        public int Age { get; set; }

        [Required(ErrorMessage = "The User Name is Requiered")]
        [MaxLength(40, ErrorMessage = "The User Name Cannot Exceed 40 Characters")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "The Password is Requiered")]
        [MaxLength(20, ErrorMessage = "The Password Cannot Exceed 20 Characters")]
        public string Password { get; set; }

        [Required(ErrorMessage = "The Mail is Requiered")]
        [MaxLength(20, ErrorMessage = "The Mail Cannot Exceed 20 Characters")]
        public string Mail { get; set; }

        [Required(ErrorMessage = "The Addres is Requiered")]
        [MaxLength(30, ErrorMessage = "The Addres Cannot Exceed 30 Characters")]
        public string Addres { get; set; }

        [Required(ErrorMessage = "The Phone is Requiered")]
        [MaxLength(20, ErrorMessage = "The Phone Cannot Exceed 20 Characters")]
        public string Phone { get; set; }

        // To generate encrypted password.
        public byte[] PasswordHash { get; set; }
        public byte[] PasswordSalt { get; set; }
    }
namespace Structure.Data.Repositories.IRepositories
{
    public interface IUserRepositorie
    {
        // Method.
        Task<int> Register(User user, string password);
        Task<string> Login(string userName, string password);
        Task<bool> UserExist(string userName);
        Task<byte[]> GetPasswordHashFromDb();
        Task<byte[]> GetPasswordSaltFromDb();
    }
}
namespace Structure.Data.Repositories
{
    public class IUser : IUserRepositorie
    {

        //Varibale.
        private readonly ApplicationDbContext _db;

        //Constructor.
        public IUser(ApplicationDbContext db)
        {
            _db = db;
        }
        
        public async Task<string> Login(string userName, string password)
        {
            var user = await _db.User.FindAsync(userName);

            if (user == null)
            {
                return "NOT FOUND"; // Usuario no encontrado
            }

            if (!VerifyPassHash(password, user.PasswordHash, user.PasswordSalt))
            {
                return "BAD CREDENTIALS"; // Credenciales inválidas
            }

            return user.Id.ToString(); // Inicio de sesión exitoso
        }

        private async Task<User> GetUserByUsername(string username)
        {
            // Lógica para obtener el usuario por nombre de usuario
            // Implementa la consulta a tu base de datos aquí

            // Ejemplo utilizando una lista en memoria como fuente de datos
            var user = _db.User.FirstOrDefaultAsync(u => u.UserName == username);
            return await user;
        }

        private bool VerifyPassHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            using (var hmac = new HMACSHA512(passwordSalt))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));

                for (int i = 0; i < computedHash.Length; i++)
                {
                    if (computedHash[i] != passwordHash[i])
                    {
                        return false; // Credenciales inválidas
                    }
                }

                return true; // Credenciales válidas
            }
        }

        public async Task<int> Register(User user, string password)
        {
            try
            {
                if (await UserExist(user.UserName))
                {
                    return -1;
                }

                CreatPassHash(password, out byte[] passwordHash, out byte[] passwordSalt);

                user.PasswordHash = passwordHash;
                user.PasswordSalt = passwordSalt;

                await _db.User.AddAsync(user);
                await _db.SaveChangesAsync();
                return user.Id;
            }
            catch (System.Exception)
            {
                
                return -500;
            }
        }

        public async Task<bool> UserExist(string userName)
        {
            if (await _db.User.AnyAsync(x => x.UserName.ToLower().Equals(userName.ToLower())))
            {
                return true;
            }  
            return false;    
        }
        

        private void CreatPassHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            //Query
            using(var hmac = new System.Security.Cryptography.HMACSHA512())
            {
                passwordHash = hmac.Key;
                passwordSalt = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }
        }

        public async Task<byte[]> GetPasswordHashFromDb()
        {
            //Query.
            var getPassHash = await _db.User.FirstOrDefaultAsync();

            if (getPassHash != null)
            {
                return getPassHash.PasswordHash;
            }
            
            return null;
        }

        public async Task<byte[]> GetPasswordSaltFromDb()
        {
            //Query.
            var getPassSalt = await _db.User.FirstOrDefaultAsync();

            if (getPassSalt != null)
            {
                return getPassSalt.PasswordSalt;
            }
            
            return null;
        }
    }
}
namespace APIAlgoTheChillSeeds.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        //Properties.
        public readonly ApplicationDbContext _db;
        private readonly IUserRepositorie _userRepositorie;
        private ResponseDto _response;

        public UserController(ApplicationDbContext db,IUserRepositorie userRepositorie)
        {
            _db = db;
            _userRepositorie = userRepositorie;
            _response = new ResponseDto();
        }


        [HttpPost("Register")]
        public async Task<ActionResult> Register(UserDto user)
        {
            //Query.
            var response = await _userRepositorie.Register(
                                new User{
                                    UserName = user.UserName                                    
                                }, user.Password);

            
            //Response validation.
            if (response == -1)
            {
                _response.IsSuccessfull = false;
                _response.Message = "User Alredy Exists";
                return BadRequest(_response);
            }

            if (response == -500)
            {
                _response.IsSuccessfull = false;
                _response.Message = "Error Creating User";
                return BadRequest(_response);
            }

            _response.Message = "User Created Successfully";
            _response.Result = response;    
            
            return Ok(_response);
        }   

        
        public bool VerifyPassHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {    
            
            //Query.
            using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
            {
                var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));  

                //check if they match character by character.
                for (int i = 0; i < computedHash.Length; i++)
                {
                    //validation.
                    if (computedHash[i] != passwordHash[i])
                    {
                        return  false;
                    }      
                } 
                return true;                    
            }
        }
    }
}
using Microsoft.EntityFrameworkCore;
using Structure.Data;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//Db Context
var connectionString = builder.Configuration.GetConnectionString("DefaulConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));

//Core.
builder.Services.AddCors();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseCors(x => x.AllowAnyOrigin()
                  .AllowAnyHeader()
                  .AllowAnyMethod());


app.UseAuthorization();

app.MapControllers();

app.Run();

Este es el error que me aparece por consola:

Unhandled exception. System.InvalidOperationException: Action 'APIAlgoTheChillSeeds.Controllers.UserController.VerifyPassHash (APIAlgoTheChillSeeds)' has more than one parameter that was specifieds bound from request body. Only one parameter per action may be bound from body. Inspect the following parameters, and use 'FromQueryAttribute' to specify bound from query, 'FromRouteAttribute' to from route, and 'FromBodyAttribute' for parameters to be bound from body:
byte[] passwordHash
byte[] passwordSalt
   at Microsoft.AspNetCore.Mvc.ApplicationModels.InferParameterBindingInfoConvention.InferParameterBindingSources(ActionModel action)
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ApiBehaviorApplicationModelProvider.OnProvidersExecuting(ApplicationModelProviderContext context)
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ApplicationModelFactory.CreateApplicationModel(IEnumerable`1 controllerTypes)
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.GetDescriptors()
   at Microsoft.AspNetCore.Mvc.ApplicationModels.ControllerActionDescriptorProvider.OnProvidersExecuting(ActionDescriptorProviderContext context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.UpdateCollection()
   at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.Initialize()
   at Microsoft.AspNetCore.Mvc.Infrastructure.DefaultActionDescriptorCollectionProvider.GetChangeToken()
   at Microsoft.Extensions.Primitives.ChangeToken.OnChange(Func`1 changeTokenProducer, Action changeTokenConsumer)
   at Microsoft.AspNetCore.Mvc.Routing.ActionEndpointDataSourceBase.Subscribe()
   at Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.GetOrCreateDataSource(IEndpointRouteBuilder endpoints)
   at Microsoft.AspNetCore.Builder.ControllerEndpointRouteBuilderExtensions.MapControllers(IEndpointRouteBuilder endpoints)
   at Program.<Main>$(String[] args) in C:\Users\leand\bootcampAngular\appAlgoTheChillSeeds\algoTheChillSeedsBackend\APIAlgoTheChillSeeds\Program.cs:line 38
2
  • 1
    por sólo leer el error, dice que estás mandando más parámetros del los que está esperando, revisa qué estás mandado. PD: Trata de poner el código en vez de imágenes, ya que habemos usuarios que no nos cargan imágenes, jeje el 11 jul. a las 22:15
  • ¡Bienvenido a Stack Overflow en español! Te invito a hacer el recorrido de bienvenida.Por favor no publiques código o mensajes de error/trazas de pila en imágenes, publica directamente el texto del código, el texto de los errores y los stack traces. Esto hace que sea menos complicado, para quien quiera ayudarte, investigar sobre el tema y hacer sus propias pruebas/adaptaciones al código, al escribir una respuesta y de esa forma aumenta tus posibilidades de encontrar la ayuda que buscas. Un saludo.
    – jachguate
    el 11 jul. a las 22:15

1 respuesta 1

0

El método para verificar el hash de contraseñas debe ser privado, porque si no ASP.NET Core entenderá que es una ruta. Por tanto, debes hacerlo privado sustituyendo public por private en el método VerifyPassHash del UserController.

Por otra parte, te recomiendo que en vez de implementar tu propia autenticación uses Identity, ya que te ahorrará reinventar la rueda y seguramente sea más seguro.

Tu Respuesta

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

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.