Ejemplo n.º 1
0
        public VerifiedUser GenerateJsonWebToken(VerifiedUser user)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var securityKey  = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.Key));
            var credentials  = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            //Create claims
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName)
            };

            //add roles to claims
            foreach (var role in user.Role)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

            var tokenDescription = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddMinutes(120),
                SigningCredentials = credentials,
                Issuer             = config.Issuer,
                Audience           = config.Issuer
            };

            var token = tokenHandler.CreateToken(tokenDescription);

            user.Token = tokenHandler.WriteToken(token);

            return(user);
        }
Ejemplo n.º 2
0
        public async Task <ApiResponse <VerifiedUser> > AuthenticateUser(UserDTO userModel)
        {
            //Get user
            var user = await _userManager.FindByNameAsync(userModel.UserName);

            //Verify if _userManager returned user and check his password
            if (user != null && await _userManager.CheckPasswordAsync(user, userModel.Password))
            {
                //Get roles
                var userRoles = await _userManager.GetRolesAsync(user);

                //Create user
                var verifiedUser = new VerifiedUser {
                    UserName = user.UserName, Role = userRoles
                };

                //Generate and assign JWT token to verified user
                verifiedUser = _jwtAuth.GenerateJsonWebToken(verifiedUser);
                return(Response <VerifiedUser> .Create(verifiedUser, true, "Logged in"));
            }

            return(Response <VerifiedUser> .Create(null, false, "Couldn't find that user"));
        }