1
votes

I am implementing Authentication and Authorization Role base in Asp.Net Web API Core 1.1 . I am using JWT token for generating token and authenticating the request but i am stucking to match the username and password with the existing database default generated tables by Identity. How to match password with PasswordHash and Register new user. Is the any example to implement Login and Registration api in .Net Core 1.1?

2

2 Answers

0
votes

You can use UserManager to create new user with method
public virtual Task<IdentityResult> CreateAsync(TUser user, string password) and

SignInManager to sign in with given password using method:
public virtual Task<SignInResult> PasswordSignInAsync(TUser user, string password, bool isPersistent, bool lockoutOnFailure)

0
votes
[HttpPost]
    public async Task<IActionResult> Register([FromBody]UserModel model)
    {

        IdentityResult result;

        if (!ModelState.IsValid) return BadRequest(ModelState);

        var user = new ApplicationUser { UserName = model.UserName, Email = model.UserName };

             result = await _userManager.CreateAsync(user, model.Password);

        if (! result.Succeeded) return  BadRequest(ModelState);

        return Ok(new {userCreated=true, userName= model.UserName });
    }

 [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody]UserModel loginViewModel)
    {
        if (ModelState.IsValid)
        {
            var userFound = await _userManager.FindByNameAsync(loginViewModel.UserName);

            if (userFound == null) return Unauthorized();

            var userId = userFound?.Id;

            // Claims, we endow this user
            var claims = new[]
            {

            new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Id, userId),
            new Claim(Helpers.Constants.Strings.JwtClaimIdentifiers.Rol, Helpers.Constants.Strings.JwtClaims.ApiAccess),
            new Claim("test2", "test2")
         };


            // Get options from app settings
            var options = _configuration.GetSection(nameof(JwtIssuerOptions));

            SymmetricSecurityKey _signingKey =  new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_configuration["SecretKey"]));

            // Configure JwtIssuerOptions


            var token = new JwtSecurityToken
            (
                issuer: options[nameof(JwtIssuerOptions.Issuer)],
                audience: options[nameof(JwtIssuerOptions.Audience)],
                claims: claims,
                expires: DateTime.UtcNow.AddMinutes(60), // token works 1 hour! (then invalidates)
                notBefore: DateTime.UtcNow,
                signingCredentials: new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256)
            );

            return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
        }

        return BadRequest();
    }