/// <summary> /// 基本用户身份验证(各系统可根据自己的实际需要,自定义验证方法,此多语言模块实现了验证并提供参考依据) /// 详细说明:判断用户是否登录,如果未登录则跳转到统一登录页面 /// 其它:统一身份认证服务地址:http://218.201.35.212:11007/ /// 创建人:张甫军 创建时间:2017年11月28日 16:24 /// </summary> public class AuthAttribute : AuthorizeAttribute { /// <summary> /// 自定义判断当前用户是否已授权 /// </summary> /// <param name="httpContext"></param> /// <returns></returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { //如果已授权,则返回true if (httpContext.Request.IsAuthenticated) { return true; } else if (AuthorizedRequest(httpContext))//判断是否已授权的请求(由统一登录页面授权成功后跳转),如果已授权成功,则返回true { return true; } else { //未授权,设置状态码为403,并跳转到统一登录页面 httpContext.Response.StatusCode = 403; return false; } } /// <summary> /// 处理未经授权的请求 /// </summary> /// <param name="filterContext"></param> protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); //自定义403为未授权,如果状态码为403,就跳转到统一登录页面 if (filterContext.HttpContext.Response.StatusCode == 403) { //判断请求地址是否为空,显然不能为空 if (filterContext.HttpContext.Request.Url != null) { //如果是ajax请求,则提示未登录 if (filterContext.HttpContext.Request.IsAjaxRequest()) { var result = new JsonResult { Data = new CommonResultResponse { Result = false, Message = "请先登录!" }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; filterContext.Result = result; } else { //组装参数,并跳转到统一登录页面 //var loginUrl = "http://218.201.35.212:11007/Account/Login"; var loginUrlTest = "http://localhost:54550/Account/Login"; var appID = "IOV.Language"; var appSecret = "3r2d25fe3"; var returnUrl = filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.Url.ToString()); var redirectUrl = string.Concat(loginUrlTest, "?", "appId=" + appID, "&secret=" + appSecret, "&languageCulture=zh-CN", "&returnUrl=", returnUrl); if (filterContext.HttpContext.Request.Url != null) filterContext.Result = new RedirectResult(redirectUrl); } } } } /// <summary> /// 说明:此函数判断是否为统一身份认证服务授权成功的回调。 /// 无论你的实现方式是什么,都应判断当前请求是否有“accessToken”参数&是否有值,如有值,就意味着当前用户登录成功。 /// </summary> /// <param name="httpContext">HTTP请求信息</param> /// <returns>是否登录成功</returns> public bool AuthorizedRequest(HttpContextBase httpContext) { if (httpContext == null || httpContext.Request == null) { return false; } //访问令牌(由统一身份认证服务颁发) var accessToken = httpContext.Request.QueryString["accessToken"]; //当前登录账号 var loginID = httpContext.Request.QueryString["loginID"]; //判断是否持有访问令牌 if (string.IsNullOrWhiteSpace(accessToken)) { return false; } else { return true; } } }