How and where to call the method of creating a Token in WebApi to perform the validation of my user?

0

Good evening! I am doing a user authentication using HMACSHA512, however I am having difficulty calling the authentication method at project start and in my controller (I am using .NET). I did this in .NET Core and it has some classes and properties that .NET does not have.

This is my code to perform all user authentication:

public class ServiceAuthentication : IServiceAuthentication
{
    public readonly IUserService _userService;
    public ServiceAuthentication(IUserService serviceUser)
    {
        _userService = serviceUser;
    }

    public async Task<string> Login(string login, string password)
    {
        var user = await _userService.FindByObject(new User { Login = login }, "Login");

        if (user == null)
            return "Usuário não encontrado!";

        if (!VerifyPassword(password, user.PasswordHash, user.PasswordSalt))
            return Messages.ERROR_AUTHENTICATED;

       return CreateToken(user);
    }

    private string CreateToken(User user)
    {
        var tokeHandler = new JwtSecurityTokenHandler();
        var key = System.Text.Encoding.ASCII.GetBytes("SUPER SECRET KEY");

        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]{
                        new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString()),
                        new Claim(ClaimTypes.Name, user.Login)
                    }),
            Expires = DateTime.Now.AddDays(1),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
        };
        var token = tokeHandler.CreateToken(tokenDescriptor);
        var tokenString = tokeHandler.WriteToken(token);
        return  tokenString;
    }

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

            for (int i = 0; i <= passwordHash.Length; i++)
                if (passwordHash[i] != computedHash[i])
                    return false;

            return true;
        }
    }

    private async Task<bool> UserExits(string login)
    {
        var user = await _userService.FindByObject(new User { Login = login }, "Login");

        if (user != null)
            return true;
        return false;
    }

    public async Task<string> Register(User user, string password)
    {
        if (await UserExits(user.Login))
            return "Usuário já existente";

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

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

        await _userService.Add(user);

        return Messages.SUCCESS;
    }

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

This is my controller where I want to call my method to validate the user:

    [System.Web.Http.Route]
public class AuthenticationController : Controller 
{
    private readonly IServiceAuthentication _service;

    public AuthenticationController(IServiceAuthentication service)
    {
        _service = service;
    }

    private const string SETTINGS = "AppSettings:Token";
    private readonly Configuration Configuration;

    public AuthenticationController(Configuration configuration)
    {
        this.Configuration = configuration;
    } 
 }

Does anyone have any ideas or have you come across this and could you explain? Thanks!

    
asked by anonymous 22.04.2018 / 04:50

0 answers