async Task <SignedInDto> GetToken(AppIdentityUser user) { if (user == null) { throw new ArgumentException(nameof(user)); } if (user.IsBlocked) { ThrowUnauthorized(); } var handler = new JwtSecurityTokenHandler(); // ReSharper disable once PossibleNullReferenceException var genericIdentity = new GenericIdentity(user.UserName, JwtBearerDefaults.AuthenticationScheme); var claimsIdentity = new ClaimsIdentity(genericIdentity, new[] { new Claim(ClaimTypes.Name, user.UserName), new Claim(ClaimTypes.Email, user.Email ?? string.Empty), new Claim(ClaimTypes.UserData, user.Id.ToString(), ClaimValueTypes.String) }); if (user.Roles?.Any() != true) { await _dbContext.Entry(user).Collection(_ => _.Roles).LoadAsync(); } // ReSharper disable once AssignNullToNotNullAttribute claimsIdentity.AddClaims(user.Roles.Select(_ => new Claim(ClaimTypes.Role, _rolesHelper.GetRoleById(_.RoleId).ToString()))); var securityToken = handler .CreateJwtSecurityToken( _authConfig.Issuer, _authConfig.Audience, signingCredentials: new SigningCredentials(_authConfig.SecurityKey, SecurityAlgorithms.RsaSha256), subject: claimsIdentity ); var result = _mapper.Map <SignedInDto>(user); result.Token = handler.WriteToken(securityToken); return(result); }
static void ConfigureUsers(IProfileExpression config, IRolesHelper rolesHelper) { config.CreateMap <SignUpDto, AppIdentityUser>() .ForMember(d => d.FirstName, opt => opt.MapFrom(s => s.FirstName.Trim())) .ForMember(d => d.LastName, opt => opt.MapFrom(s => s.LastName.Trim())) .ForMember(d => d.UserName, opt => opt.MapFrom(s => s.Email.Trim())) .ForMember(d => d.Email, opt => opt.MapFrom(s => s.Email.Trim())) .ForMember(d => d.DateOfBirth, opt => opt.MapFrom(s => s.DateOfBirth)) .ForMember(d => d.Gender, opt => opt.MapFrom(s => s.Gender)) .ForAllOtherMembers(opt => opt.Ignore()); config.CreateMap <AppIdentityUser, UserDto>(); config.CreateMap <AppIdentityUser, UserWithRolesDto>() .IncludeBase <AppIdentityUser, UserDto>() .ForMember(d => d.Roles, opt => opt.MapFrom(s => s.Roles.Select(_ => rolesHelper.GetRoleById(_.RoleId)).ToArray())); config.CreateMap <AppIdentityUser, SignedInDto>() .IncludeBase <AppIdentityUser, UserWithRolesDto>() .ForMember(d => d.Token, opt => opt.Ignore()); }