forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAspNetUser.cs
More file actions
87 lines (70 loc) · 2.55 KB
/
AspNetUser.cs
File metadata and controls
87 lines (70 loc) · 2.55 KB
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
77
78
79
80
81
82
83
84
85
86
87
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Blog.Core.Common.HttpContextUser
{
public class AspNetUser : IUser
{
private readonly IHttpContextAccessor _accessor;
private readonly ILogger<AspNetUser> _logger;
public AspNetUser(IHttpContextAccessor accessor, ILogger<AspNetUser> logger)
{
_accessor = accessor;
_logger = logger;
}
public string Name => GetName();
private string GetName()
{
if (IsAuthenticated() && _accessor.HttpContext.User.Identity.Name.IsNotEmptyOrNull())
{
return _accessor.HttpContext.User.Identity.Name;
}
else
{
if (!string.IsNullOrEmpty(GetToken()))
{
var getNameType = Permissions.IsUseIds4 ? "name" : "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";
return GetUserInfoFromToken(getNameType).FirstOrDefault().ObjToString();
}
}
return "";
}
public int ID => GetClaimValueByType("jti").FirstOrDefault().ObjToInt();
public bool IsAuthenticated()
{
return _accessor.HttpContext.User.Identity.IsAuthenticated;
}
public string GetToken()
{
return _accessor.HttpContext?.Request?.Headers["Authorization"].ObjToString().Replace("Bearer ", "");
}
public List<string> GetUserInfoFromToken(string ClaimType)
{
var jwtHandler = new JwtSecurityTokenHandler();
var token = "";
token = GetToken();
// token校验
if (token.IsNotEmptyOrNull() && jwtHandler.CanReadToken(token))
{
JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);
return (from item in jwtToken.Claims
where item.Type == ClaimType
select item.Value).ToList();
}
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();
}
}
}