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

Asked

Viewed 65 times

0

Good night! I’m doing a user authentication using HMACSHA512, but I’m having a hard time calling the authentication method at project start and in my controller (I’m using .NET). I did it in . NET Core and it has some classes and properties that the . normal NET does not have.

This is my code to perform all user authentications:

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 idea or has already come across this and could you explain it to me? Thank you!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.