BaseController.cs
3.65 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
using Hh.Mes.Common;
using Hh.Mes.Common.Json;
using Hh.Mes.Pojo.System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text.Json;
namespace Hh.Mes.Api.Controllers
{
public class BaseController : ControllerBase
{
/// <summary>
/// 上下文
/// </summary>
public HttpContext context;
/// <summary>
/// 获取用户
/// 注意配置文件(appsettings)设置【RedisDb】要和中控系统【RedisDb】保持一致,否则取不到用户信息
/// </summary>
public UserAuthSession GetUser(HttpContext httpContext)
{
try
{
var token = GetToken(httpContext);
if (string.IsNullOrWhiteSpace(token))
{
return null;
}
var json = JwtEncryption.Decode(token);
return JsonSerializer.Deserialize<UserAuthSession>(json);
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// 获取 tokens
/// </summary>
public string GetToken(HttpContext httpContext)
{
var token = httpContext.Request.Query[Program.tokens];
if (string.IsNullOrEmpty(token)) token = httpContext.Request.Cookies[Program.tokens];
if (string.IsNullOrEmpty(token)) token = httpContext.Request.Headers[Program.tokens];
return token;
}
public string Serialize(object result)
{
return JsonHelper.Instance.Serialize(result);
}
/// <summary>
/// 获取客户端ip 注意先依赖注入context
/// </summary>
/// <returns></returns>
public string GetIp()
{
string ip = context.Connection.RemoteIpAddress.ToString();
return ip;
}
}
/// <summary>
/// 用户验证 ,在全局忽略下,做二次保险验证
/// </summary>
public class ValidateUserAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
try
{
string token = context.HttpContext.Request.Query[Program.tokens];
if (string.IsNullOrEmpty(token)) token = context.HttpContext.Request.Cookies[Program.tokens];
if (string.IsNullOrEmpty(token)) token = context.HttpContext.Request.Headers[Program.tokens];
if (string.IsNullOrWhiteSpace(token))
{
ContextResponse(context);
return;
}
var json = JwtEncryption.Decode(token);
var user = JsonSerializer.Deserialize<UserAuthSession>(json);
// 可以将用户信息存储到 HttpContext.Items 供后续使用
context.HttpContext.Items["Account"] = user.Account;
}
catch (Exception)
{
ContextResponse(context);
return;
}
base.OnActionExecuting(context);
}
private void ContextResponse(ActionExecutingContext context)
{
context.HttpContext.Response.ContentType = "application/json";
context.Result = new ContentResult
{
Content = "{\"code\":401,\"status\":false,\"message\":\"Tokens失效 请重新登入\",\"result\":null}",
StatusCode = StatusCodes.Status200OK,
ContentType = "application/json"
};
}
}
}