[AttributeUsage(AttributeTargets.Class)]
public sealed class CustomAuthorization : AuthorizeAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext filterContext)
{
HttpContextAccessor contextAccessor = new HttpContextAccessor();
var userClaim = contextAccessor.HttpContext.User.FindFirst("Jti");
long.TryParse(userClaim.Value, out long userId);
var controllerInfo = filterContext.ActionDescriptor as ControllerActionDescriptor;
CustomMemoryCacher memoryCacher = CustomMemoryCacher.CacheCreator();
List<KullaniciYetkileriDto> yetkiler = (List<KullaniciYetkileriDto>) memoryCacher.Get(userId);
if (filterContext != null && yetkiler != null)
{
filterContext.Result = new JsonResult(
new { HttpStatusCode.Forbidden });
filterContext.HttpContext.Response.StatusCode = 403;
}
else
{
filterContext.Result = new JsonResult(
new { HttpStatusCode.Unauthorized });
filterContext.HttpContext.Response.StatusCode = 401;
}
}
}
userClaim空值
我想获取用户ID值。我需要从OnAuthorization方法内的声明中检索用户信息。但是我有一个错误。问题出在哪里?
是的,我使用AddJwtBearer。他正在令牌。是的,我使用AddJwtBearer。他正在令牌。
var roles = await _userManager.GetRolesAsync(user);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, user.Id.ToString()),
};
var claimsIdentity = new ClaimsIdentity(claims, "Token");
claimsIdentity.AddClaims(roles.Select(role => new Claim("roles", role)));
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_config["Tokens:Issuer"],
_config["Tokens:Issuer"],
claimsIdentity.Claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
var tokenHandler = new { token = new JwtSecurityTokenHandler().WriteToken(token) };
//giriş yapanın birim id si cachelenir
var dto = new TokenModel
{
//TODO ilerde lazım olacak user propertyleri eklenecek
Token = tokenHandler.token,
UserDto = new ApplicationUserDto
{
UserName = user.UserName,
Email = user.Email,
LanguageId = user.LanguageId,
BirimId = enYetkiliOlduguBirim.BirimId // default seçilen birim
}
//Mapper.Map<ApplicationUser, ApplicationUserDto>(user)
};
ResultData = dto;
ResultMessage = "Token created successfully";
StatusCode = StatusCodes.Status200OK;
//Giriş yapabilen kullanıcının rolleri ve rollerine ait yetkileri cachelenir
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetPriority(CacheItemPriority.Normal)
.SetSlidingExpiration(TimeSpan.FromDays(1));
CustomMemoryCacher memoryCacher = CustomMemoryCacher.CacheCreator();
loginCacheDto.KullaniciId = user.Id;
loginCacheDto.EnYetkiliOlduguBirimId = enYetkiliOlduguBirim.BirimId;
loginCacheDto.BirimId = enYetkiliOlduguBirim.BirimId;
memoryCacher.Set(user.Id, loginCacheDto, cacheEntryOptions);
YetkileriGetir(enYetkiliOlduguBirim.BirimId, user.Id);
}
给出错误的部分在baseentity类中运行。
public class EntityBase
{
[Display(Name = "Ols. Kullanıcı")]
[Required(ErrorMessage = "Kullanıcı Gerekli")]
//[MaxLength()]
[MinLength(0)]
public long? ApplicationUserId
{
get
{
return applicationUserId;
}
set
{
HttpContextAccessor contextAccessor = new HttpContextAccessor();
var userClaim = contextAccessor.HttpContext.User.FindFirst("jti");
long.TryParse(userClaim.Value, out long userId);
applicationUserId = value ?? userId;
}
}
}
答案 0 :(得分:0)
我测试时效果很好。但是,您首先需要检查userClaim
是否不为null或User.Identity.IsAuthenticated
是否为true。在登录用户之前点击代码时,它将引发错误。
var userClaim = contextAccessor.HttpContext.User.FindFirst("Jti");
if(userClaim!= null)
{
long.TryParse(userClaim.Value, out long userId);
}