yusijie
2 天以前 6866dbd4b0b8703811872669179a68841eea803d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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;
    }
}