我在项目中使用了JWT。我创建了一个自定义授权属性,但是AuthorizationFilterContext
为空。当我在控制器中使用相同的东西时,我可以访问上下文,但是在属性中上下文为空。
这是我的登录控制器:
public async Task<IActionResult> Login([FromBody] LoginViewModel login)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var identity = await GetClaimsIdentity(login.Username, login.Password);
if (identity == null)
{
return BadRequest("username or password is wrong");
}
var response = new
{
id = identity.Claims.Single(c => c.Type == "id").Value,
auth_token = await _jwtFactory.GenerateEncodedToken(login.Username, identity),
expires_in = (int)_jwtOptions.ValidFor.TotalSeconds,
};
//string UserId = User.FindFirst("id").Value;
return Ok(JsonConvert.SerializeObject(response, _serializerSettings));
}
这是属性:
public class CustomCheckPermissionAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private int _permissionId = 0;
public CustomCheckPermissionAttribute(int _permissionId)
{
this._permissionId = _permissionId;
}
public void OnAuthorization(AuthorizationFilterContext filterContext)
{
var x = filterContext.HttpContext.User.FindFirst("id").Value;
}
}