Проблема с использованием Identity Server
в моем проекте который я пишу на Asp.net web api (https://github.com/NeTBoyBot/SolarLabProject) При попытке перехода с чистого Identity на Identity Server возникла небольшая проблема. При обращении к HttpContextAccessor-у и попытке получить у него клеймы, он возвращает мне их пустыми. На чистой версии айдентити при обращении к нему же, все прекрасно. На гите есть две ветки на master ветке чистый айдентити, на Identity ветке моя безуспешная попытка имплементации данного функционала.
public async Task<string> Login(LoginUserRequest userLogin, CancellationToken cancellation)
{
var existingUser = await _userManager.FindByEmailAsync(userLogin.Email);
if (existingUser == null)
throw new Exception($"Пользователь с email '{userLogin.Email}' не существует");
var checkPass = await _userManager.CheckPasswordAsync(existingUser, userLogin.Password);
if (!checkPass)
throw new Exception("Неверная почта или пароль");
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, existingUser.Id.ToString()),
new Claim(ClaimTypes.Name, existingUser.UserName)
};
var userRole = await _userManager.GetRolesAsync(existingUser);
claims.AddRange(userRole.Select(role => new Claim(ClaimTypes.Role, role)));
var secretKey = _configuration["Jwt:Key"];
var token = new JwtSecurityToken
(
claims: claims,
expires: DateTime.UtcNow.AddDays(1),
notBefore: DateTime.UtcNow,
signingCredentials: new SigningCredentials(
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)),
SecurityAlgorithms.HmacSha256)
);
var result = new JwtSecurityTokenHandler().WriteToken(token);
if (cancellation.IsCancellationRequested)
throw new OperationCanceledException();
return result;
}
public async Task<InfoUserResponse> GetCurrentUser(CancellationToken cancellation)
{
var claim = _httpContextAccessor.HttpContext.User.Claims;
var claimId = claim.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
//var claimId = _claimAccessor.UserId;
if (string.IsNullOrWhiteSpace(claimId))
return null;
var user = await _userManager.FindByIdAsync(claimId);
if (user == null)
throw new Exception($"Не найдент пользователь с идентификаторром {claimId}");
var userResponse = _mapper.Map<InfoUserResponse>(user);
userResponse.Id = Guid.Parse(user.Id);
userResponse.Role = await _userManager.GetRolesAsync(user);
return userResponse;
}
Код регистрации IHttpContextAccessor-a
builder.Services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddHttpContextAccessor(); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer( options => {
var secretKey = builder.Configuration["Jwt:Key"];
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateActor = false,
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey))
};
});
builder.Services.AddAuthorization();