liaoxujun@qq.com
2024-02-28 9f8e542b9b74fe18a6a4e0a00fef4b50e3e62581
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
/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2021/1/31 21:45:10
 *        Description: 暂无
 ***********************************************************************/
 
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using CoreCms.Net.Utility.Extensions;
using Microsoft.AspNetCore.Http;
 
namespace CoreCms.Net.Auth.HttpContextUser
{
    public class AspNetUser : IHttpContextUser
    {
        private readonly IHttpContextAccessor _accessor;
 
        public AspNetUser(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }
 
        public string Name => _accessor.HttpContext.User.Identity.Name;
        public int ID => GetClaimValueByType("jti").FirstOrDefault().ObjectToInt();
 
        public bool IsAuthenticated()
        {
            return _accessor.HttpContext.User.Identity.IsAuthenticated;
        }
 
        public string GetToken()
        {
            return _accessor.HttpContext.Request.Headers["Authorization"].ObjectToString().Replace("Bearer ", "");
        }
 
        public List<string> GetUserInfoFromToken(string ClaimType)
        {
 
            var jwtHandler = new JwtSecurityTokenHandler();
            if (!string.IsNullOrEmpty(GetToken()))
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(GetToken());
 
                return (from item in jwtToken.Claims
                        where item.Type == ClaimType
                        select item.Value).ToList();
            }
            else
            {
                return new List<string>() { };
            }
        }
 
        public IEnumerable<Claim> GetClaimsIdentity()
        {
            return _accessor.HttpContext.User.Claims;
        }
 
        public List<string> GetClaimValueByType(string ClaimType)
        {
 
            return (from item in GetClaimsIdentity()
                    where item.Type == ClaimType
                    select item.Value).ToList();
 
        }
    }
}