SSOAuthAttribute.cs
1.68 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
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace WebApp
{
/// <summary>
/// 采用Attribute的方式验证登录
/// </summary>
public class SSOAuthAttribute : ActionFilterAttribute
{
public const string Token = "Token";
private IAuth _auth;
public SSOAuthAttribute(IAuth auth)
{
_auth = auth;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var token = "";
//Token by QueryString
var request = filterContext.HttpContext.Request;
if (!string.IsNullOrEmpty(request.Query[Token]))
{
token = request.Query[Token];
filterContext.HttpContext.Response.Cookies.Append(Token, token);
}
else if (request.Cookies[Token] != null) //从Cookie读取Token
{
token = request.Cookies[Token];
}
if (string.IsNullOrEmpty(token))
{
//直接登录
filterContext.Result = LoginResult("");
return;
}
else
{
//验证
if (_auth.CheckLogin(token) == false)
{
//会话丢失,跳转到登录页面
filterContext.Result = LoginResult("");
return;
}
}
//base.OnActionExecuting(filterContext);
}
public virtual ActionResult LoginResult(string username)
{
return new RedirectResult("/Login/Index");
}
}
}