ASP.NET MVC SSO单点登录设计与实现代码(2)

public class SSOAuthAttribute : ActionFilterAttribute { public const string SessionKey = "SessionKey"; public const string SessionUserName = "SessionUserName"; public override void OnActionExecuting(ActionExecutingContext filterContext) { var cookieSessionkey = ""; var cookieSessionUserName = ""; //SessionKey by QueryString if (filterContext.HttpContext.Request.QueryString[SessionKey] != null) { cookieSessionkey = filterContext.HttpContext.Request.QueryString[SessionKey]; filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(SessionKey, cookieSessionkey)); } //SessionUserName by QueryString if (filterContext.HttpContext.Request.QueryString[SessionUserName] != null) { cookieSessionUserName = filterContext.HttpContext.Request.QueryString[SessionUserName]; filterContext.HttpContext.Response.Cookies.Add(new HttpCookie(SessionUserName, cookieSessionUserName)); } //从Cookie读取SessionKey if (filterContext.HttpContext.Request.Cookies[SessionKey] != null) { cookieSessionkey = filterContext.HttpContext.Request.Cookies[SessionKey].Value; } //从Cookie读取SessionUserName if (filterContext.HttpContext.Request.Cookies[SessionUserName] != null) { cookieSessionUserName = filterContext.HttpContext.Request.Cookies[SessionUserName].Value; } if (string.IsNullOrEmpty(cookieSessionkey) || string.IsNullOrEmpty(cookieSessionUserName)) { //直接登录 filterContext.Result = SsoLoginResult(cookieSessionUserName); } else { //验证 if (CheckLogin(cookieSessionkey, filterContext.HttpContext.Request.RawUrl) == false) { //会话丢失,跳转到登录页面 filterContext.Result = SsoLoginResult(cookieSessionUserName); } } base.OnActionExecuting(filterContext); } public static bool CheckLogin(string sessionKey, string remark = "") { var httpClient = new HttpClient { BaseAddress = new Uri(ConfigurationManager.AppSettings["SSOPassport"]) }; var requestUri = string.Format("api/Passport?sessionKey={0}&remark={1}", sessionKey, remark); try { var resp = httpClient.GetAsync(requestUri).Result; resp.EnsureSuccessStatusCode(); return resp.Content.ReadAsAsync<bool>().Result; } catch (Exception ex) { throw ex; } } private static ActionResult SsoLoginResult(string username) { return new RedirectResult(string.Format("{0}/passport?appkey={1}&username={2}", ConfigurationManager.AppSettings["SSOPassport"], ConfigurationManager.AppSettings["SSOAppKey"], username)); } }

示例SSO验证特性使用方法:

[SSOAuth] public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } }

总结:

从草稿示例代码中可以看到代码性能上还有很多优化的地方,还有SSO应用授权登陆页面的用户账号不存在、密码错误等一系列的提示信息等。在业务代码运行基本正确的后期,可以考虑往更多的安全性层面优化,比如启用AppSecret私钥签名验证,IP范围验证,固定会话请求攻击、SSO授权登陆界面的验证码、会话缓存自动重建、SSo服务器、缓存的水平扩展等。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdppws.html