using System;
|
using System.Net;
|
using System.Net.Http;
|
using System.Security.Claims;
|
using System.Threading;
|
using System.Threading.Tasks;
|
using System.Web.Http;
|
using System.Web.Http.Controllers;
|
using System.Web.Http.Filters;
|
using WebAPI.Utility;
|
|
public class JwtAuthorizeAttribute : AuthorizationFilterAttribute
|
{
|
// 同步鉴权
|
public override void OnAuthorization(HttpActionContext actionContext)
|
{
|
// 检查匿名访问
|
if (IsAnonymousAllowed(actionContext)) return;
|
|
// 获取Token
|
var token = GetTokenFromHeader(actionContext);
|
if (string.IsNullOrEmpty(token))
|
{
|
HandleUnauthorized(actionContext);
|
return;
|
}
|
|
// 验证Token
|
var principal = JWTHelper.ValidateToken(token, "123");
|
if (principal == null)
|
{
|
HandleUnauthorized(actionContext);
|
return;
|
}
|
|
// 设置用户
|
actionContext.RequestContext.Principal = principal;
|
}
|
|
// 异步鉴权(满足WebAPI 2要求,兼容.NET4.5)
|
public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
|
{
|
OnAuthorization(actionContext);
|
|
return Task.FromResult(0);
|
}
|
|
// 是否允许匿名访问
|
private bool IsAnonymousAllowed(HttpActionContext context)
|
{
|
return
|
context.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0 ||
|
context.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0;
|
}
|
|
// 从Header提取Token
|
private string GetTokenFromHeader(HttpActionContext context)
|
{
|
var authHeader = context.Request.Headers.Authorization;
|
if (authHeader != null
|
&& authHeader.Scheme.Equals("Bearer", StringComparison.OrdinalIgnoreCase)
|
&& !string.IsNullOrEmpty(authHeader.Parameter))
|
{
|
return authHeader.Parameter;
|
}
|
return null;
|
}
|
|
// 401 未授权
|
private void HandleUnauthorized(HttpActionContext context)
|
{
|
var response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
|
response.Content = new StringContent("未授权,请登录后重试");
|
context.Response = response;
|
}
|
}
|