forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJwtTokenAuth.cs
More file actions
57 lines (51 loc) · 1.62 KB
/
JwtTokenAuth.cs
File metadata and controls
57 lines (51 loc) · 1.62 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
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Blog.Core.AuthHelper
{
/// <summary>
///
/// </summary>
public class JwtTokenAuth
{
/// <summary>
///
/// </summary>
private readonly RequestDelegate _next;
/// <summary>
///
/// </summary>
/// <param name="next"></param>
public JwtTokenAuth(RequestDelegate next)
{
_next = next;
}
/// <summary>
///
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
public Task Invoke(HttpContext httpContext)
{
//检测是否包含'Authorization'请求头
if (!httpContext.Request.Headers.ContainsKey("Authorization"))
{
return _next(httpContext);
}
//var tokenHeader = httpContext.Request.Headers["Authorization"].ToString();
var tokenHeader = httpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
TokenModelJWT tm = JwtHelper.SerializeJWT(tokenHeader);
//授权
var claimList = new List<Claim>();
var claim = new Claim(ClaimTypes.Role, tm.Role);
claimList.Add(claim);
var identity = new ClaimsIdentity(claimList);
var principal = new ClaimsPrincipal(identity);
httpContext.User = principal;
return _next(httpContext);
}
}
}