wangxinhui
2024-12-26 78b99e5348592a29ca1393a5e13db619cc4eba56
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
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Net;
using System.Security.Claims;
using WIDESEA_Core.Configuration;
using WIDESEA_Core.Extensions;
using WIDESEA_Core.ManageUser;
using WIDESEA_Core.Utilities;
 
namespace WIDESEA_Core.Filters
{
    public interface IFixedTokenFilter : IFilterMetadata
    {
        AuthorizationFilterContext OnAuthorization(AuthorizationFilterContext context);
    }
    public class FixedTokenAttribute : Attribute, IFixedTokenFilter, IAllowAnonymous
    {
        public AuthorizationFilterContext OnAuthorization(AuthorizationFilterContext context)
        {
            string fixedoken = "";
            //如果token已失效,直接获取header里的token
            if (!context.HttpContext.User.Identity.IsAuthenticated)
            {
                fixedoken = context.HttpContext.Request.Headers[AppSetting.TokenHeaderName];
                fixedoken = fixedoken?.Replace("Bearer ", "");
                //判断是否传入了token
                if (string.IsNullOrEmpty(fixedoken))
                {
                    return context.Unauthorized("没有传入token");
                }
                //解析token
                int userId = JwtHelper.GetUserId(fixedoken);
                if (userId <= 0)
                {
                    return context.Unauthorized("token不正确");
                }
                context.AddIdentity(userId);
            }
            else
            {
                fixedoken = ((ClaimsIdentity)context.HttpContext.User.Identity)
                ?.BootstrapContext?.ToString();
            }
            //判断当前用户的token与缓存的token是否相同
            if (UserContext.Current.Token != fixedoken)
            {
                context.FilterResult(HttpStatusCode.Unauthorized, "token已失效");
            }
            return context;
        }
    }
}