예제 #1
0
        private JToken GetToken(string cookieKey, NameValueCollection param)
        {
            var result = OAuthHelper.PostRequest(JwellConfig.GetAppSetting("baseInfoForTokenUrl"), param);
            var value  = JObject.Parse(result);

            //取得Token存到Cookie里面
            return(value[cookieKey]);
        }
예제 #2
0
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <param name="cookieKey"></param>
        /// <returns></returns>
        public static string GetUserInfo(string token, string cookieKey)
        {
            var param = new NameValueCollection
            {
                [cookieKey] = token
            };

            return(PostRequest(JwellConfig.GetAppSetting("tokenApplyForUserInfoUrl"), param));
        }
예제 #3
0
        /// <summary>
        /// 回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        public ActionResult AuthorizationCallBack(string code, string state, string returnUrl)
        {
            string cookieKey   = JwellConfig.GetAppSetting("accessToken");
            var    stateCookie = Request.Cookies["state"];

            //判断State是否一致
            if (stateCookie != null && stateCookie.Value.Equals(state))
            {
                //stateCookie.Expires = DateTime.Now.AddDays(-1); //内存Cookie
                //stateCookie.Path = JwellConfig.AppSettings("WebRootPath");
                System.Web.HttpContext.Current.Response.AppendCookie(stateCookie);

                var param = new NameValueCollection
                {
                    ["clientId"]     = JwellConfig.GetAppSetting("clientId"),
                    ["clientSecret"] = JwellConfig.GetAppSetting("clientSecret"),
                    ["redirectUrl"]  = JwellConfig.GetAppSetting("redirectUrl"),
                    ["code"]         = code,
                    ["grantType"]    = "authorizationCode"
                };
                //根据Code申请Token
                var token = GetToken(cookieKey, param);
                if (token != null)
                {
                    int expireTime = 0;
                    int.TryParse(JwellConfig.GetAppSetting("codeExpire"), out expireTime);
                    var cookie = new HttpCookie(cookieKey, token.Value <string>())
                    {
                        //cookie过期时间固定设置为12小时,与token过期时间一致
                        Expires = DateTime.Now.AddHours(expireTime)
                    };

                    var userInfo = GetUserInfo(token.Value <string>(), cookieKey);
                    Request.RequestContext.HttpContext.Session["userContext"] = userInfo;

                    System.Web.HttpContext.Current.Response.AppendCookie(cookie);
                    if (returnUrl.Contains("~")) //解决前端URl存在#的问题
                    {
                        returnUrl = returnUrl.Replace("~", "#");
                    }
                    if (string.IsNullOrEmpty(returnUrl))
                    {
                        return(RedirectToAction("Index", "register"));
                    }
                    return(Redirect(returnUrl));
                }
            }
            return(Redirect(OAuthHelper.GenerateLoginUrl(this.Url.Action("AuthorizationCallBack", "OAuth", null, Request.Url.Scheme),
                                                         $"http://{HttpContext.Request.Url.Authority}/register/index")));
        }
예제 #4
0
        /// <summary>
        /// 回调
        /// </summary>
        /// <param name="code">此处code为employeeID</param>
        /// <param name="state"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        public ActionResult AuthorizationCallBack(string code, string state, string returnUrl)
        {
            string cookieKey = JwellConfig.GetAppSetting("accessToken");


            if (JwellConfig.GetAppSetting("scope") == ApplicationConstant.BASEINFO)
            {
                var param = new NameValueCollection
                {
                    ["clientId"]     = JwellConfig.GetAppSetting("clientId"),
                    ["clientSecret"] = JwellConfig.GetAppSetting("clientSecret"),
                    ["code"]         = code,
                    ["grantType"]    = "authorizationCode"
                };
                //根据Code申请Token
                var token = GetToken(cookieKey, param);
                if (token != null)
                {
                    int expireTime = 0;
                    int.TryParse(JwellConfig.GetAppSetting("codeExpire"), out expireTime);
                    var cookie = new HttpCookie(cookieKey, token.Value <string>())
                    {
                        //cookie过期时间固定设置为12小时,与token过期时间一致
                        Expires = DateTime.Now.AddHours(expireTime)
                    };

                    var userInfo = GetUserInfo(token.Value <string>(), cookieKey);
                    Request.RequestContext.HttpContext.Session["userContext"] = userInfo;

                    System.Web.HttpContext.Current.Response.AppendCookie(cookie);
                    if (!string.IsNullOrWhiteSpace(returnUrl))
                    {
                        if (returnUrl.Contains("~")) //解决前端URl存在#的问题
                        {
                            returnUrl = returnUrl.Replace("~", "#");
                        }
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Home"));
                    }
                    return(Redirect(returnUrl));
                }
            }
            return(Redirect(OAuthHelper.GenerateLoginUrl(this.Url.Action("AuthorizationCallBack", "OAuth", null, Request.Url.Scheme),
                                                         $"http://{HttpContext.Request.Url.Authority}/Home/index")));
        }
        /// <summary>
        /// 进行页面验证,查看Token是否存在
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.ActionDescriptor.GetCustomAttributes(false).Any(g => g.GetType() == typeof(AllowAnonymousAttribute)))
            {
                base.OnAuthorization(filterContext);
                return;
            }
            var token = filterContext.HttpContext.Request.Cookies[JwellConfig.GetAppSetting("AccessToken")];

            if (token != null && !string.IsNullOrEmpty(token.Value))
            {
                return;
            }
            var returnUri = filterContext.HttpContext.Request.Url.ToString();
            var urlHelper = new UrlHelper(filterContext.RequestContext);

            filterContext.Result = new RedirectResult(OAuthHelper.GenerateLoginUrl(urlHelper.Action("AuthorizationCallBack", "OAuth", null, filterContext.HttpContext.Request.Url.Scheme), returnUri));
        }
예제 #6
0
        /// <summary>
        /// 参数验证
        /// </summary>
        /// <param name="responseType"></param>
        /// <param name="scope"></param>
        /// <returns></returns>
        private bool Verification(string responseType, string scope)
        {
            bool isValid = true;

            if (string.IsNullOrWhiteSpace(responseType) && string.IsNullOrWhiteSpace(scope))
            {
                isValid = false;
            }
            else
            {
                if (responseType != JwellConfig.GetAppSetting("responseType"))
                {
                    isValid = false;
                }
                if (scope != JwellConfig.GetAppSetting("scope"))
                {
                    isValid = false;
                }
            }
            return(isValid);
        }
예제 #7
0
        /// <summary>
        /// 登出方法
        /// </summary>
        public ActionResult LogOut()
        {
            string accessToken = JwellConfig.GetAppSetting("AccessToken");

            StringBuilder fullLogoutUri = new StringBuilder().Append(JwellConfig.GetAppSetting("SSOLogoutUri"));
            var           cookies       = HttpContext.Request.Cookies[accessToken];

            if (cookies != null)
            {
                fullLogoutUri.Append("?").
                Append(accessToken).Append("=").Append(cookies.Value);
                cookies.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(cookies);
                Request.Cookies.Remove(accessToken);
            }

            string result = HttpClientHelper.Post(fullLogoutUri.ToString(), string.Empty);

            //返回系统首页
            return(Redirect($"http://{HttpContext.Request.Url.Authority}"));
        }
예제 #8
0
        /// <summary>
        /// 生成授权登录登录地址
        /// </summary>
        /// <returns></returns>
        public static string GenerateLoginUrl(string authUri, string returnUrl)
        {
            // 用于防止跨站请求伪造(CSRF)攻击
            var state  = Guid.NewGuid().ToString("N");
            var cookie = new HttpCookie("state", state)
            {
                //Path = JwellConfig.AppSettings("WebRootPath")
                HttpOnly = true
            };

            HttpContext.Current.Response.AppendCookie(cookie);
            var fullUri = new StringBuilder();

            fullUri.AppendFormat("{0}?", JwellConfig.GetAppSetting("StateApplyForCodeUrl"))
            .AppendFormat("responseType={0}", JwellConfig.GetAppSetting("responseType"))
            .AppendFormat("&scope={0}", JwellConfig.GetAppSetting("scope"))
            .AppendFormat("&clientId={0}", JwellConfig.GetAppSetting("clientId"))             //项目标示
            .AppendFormat("&redirectUrl={0}",
                          HttpUtility.UrlEncode(authUri, Encoding.UTF8))                      //验证地址,申请Token,写入Cookie
            .AppendFormat("&state={0}", state)
            .AppendFormat("&returnUrl={0}", HttpUtility.UrlEncode(returnUrl, Encoding.UTF8)); //验证通过转跳地址
            return(fullUri.ToString());
        }
예제 #9
0
 /// <summary>
 /// 是否是有效域名
 /// </summary>
 /// <returns></returns>
 protected bool IsValidDomainName()
 {
     return(HttpContext.Request.UrlReferrer.Host ==
            JwellConfig.GetAppSetting("Host"));
 }