Blame view

sys/Hh.Mes.Service/SystemAuth/SSO/SSOAuthAttribute.cs 1.87 KB
赖素文 authored
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
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Hh.Mes.Service.SystemAuth
{
    /// <summary>
    /// 采用Attribute的方式验证登录
    /// </summary>
    public class SSOAuthAttribute : ActionFilterAttribute
    {
        public const string token = "Token";
        public const string referer = "Referer";
        public const string origin = "Origin";

        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[SSOAuthAttribute.token]))
            {
                token = request.Query[SSOAuthAttribute.token];

                filterContext.HttpContext.Response.Cookies.Append(SSOAuthAttribute.token, token);
            }
            else if (request.Cookies[SSOAuthAttribute.token] != null)  //Cookie读取Token
            {
                token = request.Cookies[SSOAuthAttribute.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");
        }
    }
}