Esempio n. 1
0
        public async Task <string> GenerateToken(DetailedUserDto user, string keyWord)
        {
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Username)
            };

            var roles = await _userManager.GetRolesAsync(_mapper.Map <User>(user));

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

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyWord));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token));
        }
Esempio n. 2
0
        public async Task <IActionResult> UpdateUser(DetailedUserDto user)
        {
            var userId = user.Id;
            var claim  = User.FindFirst(ClaimTypes.NameIdentifier);

            if (userId != int.Parse(claim.Value))
            {
                return(Unauthorized());
            }

            var existingUser = await _repo.GetUser(userId);

            _mapper.Map(user, existingUser);

            if (await _repo.SaveAll())
            {
                return(NoContent());
            }

            throw new ApplicationException($"Updating user {userId} failed on save");
        }