WebApi 權限驗證方式(特性)

/// <summary>
/// 自定義權限驗證
/// </summary>
/// <param name="context"></param>
public void OnAuthorization(AuthorizationFilterContext context)
{

var user = context.HttpContext.User;
var header = context.HttpContext.Request.Headers["Authorization"];

if (!user.Identity.IsAuthenticated)
{
// it isn't needed to set unauthorized result
// as the base class already requires the user to be authenticated
// this also makes redirect to a login page work properly
//context.Result = new UnauthorizedResult();
//return;
throw new UnauthorizeException();
}redis

if (Permission == null && AuthCheckApi == false)
return;緩存

var pemissions = context.HttpContext.User.Claims.First(x => x.Type == "Pemission");
IEnumerable<string> pemissionList = pemissions != null ? JsonConvert.DeserializeObject<List<string>>(pemissions.Value) : null;ui

if (AuthCheckApi == true)
{
//TODO: 請求參數中獲取permission參數。 跟token比對。 若是包含 return; 不包含401
var acka = context.HttpContext.Request.Query["permission"].ToArray();
Console.WriteLine(Permission);
foreach (string item in pemissionList)
{
if (item.Equals(acka.First()))
return;
}
}this


if (Permission != null)
{
foreach (string item in pemissionList)
{
if (item.Equals(Permission))
return;
}
}jwt

 

throw new UnauthorizeException();
//TODO: 把失效用戶存在redis緩存中, 查詢是否失效用戶
//登出時將相關的信息好比用戶名存儲在redis中 修改某用戶權限也讓他失效 jwt中解析出用戶名去redis中查找
//每次登錄 從失效列表刪除blog


}token

相關文章
相關標籤/搜索