


This article mainly introduces ASP.NET MVC SSO single sign-on design and implementation. It has certain reference value. Those who are interested can learn more.
Experimental environment configuration
The HOST file configuration is as follows:
127.0.0.1 app.com
127.0.0.1 sso.com
IIS configuration is as follows:
#The application pool uses .Net Framework 4.0
Pay attention to the domain names bound to IIS, which are two completely different domain names.
app.com website configuration is as follows:
sso.com website configuration is as follows:
memcachedCache:
Database configuration:
Authorization verification process demonstration:
Visit: http://app.com in the browser address bar. If the user has not logged in, the website will automatically redirect Go to: http://sso.com/passport, and pass the corresponding AppKey application ID through QueryString parameters. The running screenshot is as follows: URL address: http://sso.com/passport ?appkey=670b14728ad9902aecba32e22fa4f6bd&username=## After entering the correct login account and password, click the login button and the system will automatically redirect 301 to the application and the homepage will drop. After the destruction is successful, it will be as shown below. :
Since SSO authorization login is performed under different domains, QueryString method is used to return the authorization ID. Cookies can be used on websites of the same domain. Since the 301 redirect request is sent by the browser, if the authorization identifier is placed in Handers, it will be lost when the browser redirects. After the redirection is successful, the program automatically writes the authorization mark into the cookie. When clicking on other page addresses, the authorization mark information will no longer be seen in the URL address bar. Cookie settings are as follows:
# Subsequent authorization verification after successful login (access to other pages that require authorization):
Verification address: http:// sso.com/api/passport?
sessionkey=xxxxxx&remark=xxxxxxReturn result: true, false
The client can choose to prompt the user for authorization based on the actual business situation Lost and needs to be reauthorized. By default, it is automatically redirected to the SSO login page, namely: http://sso.com/passport?appkey=670b14728ad9902aecba32e22fa4f6bd&username=seo@ljja.cn. At the same time, the email address text box on the login page will automatically complete the user's login account. The user only needs to Just enter the login password. After successful authorization, the session validity period will be automatically extended for one year.
SSO database verification log:User authorization verification log:
User authorization session Session:
Database user account and application information:
Core code of application authorization login verification page:
/// <summary> /// 公钥:AppKey /// 私钥:AppSecret /// 会话:SessionKey /// </summary> public class PassportController : Controller { private readonly IAppInfoService _appInfoService = new AppInfoService(); private readonly IAppUserService _appUserService = new AppUserService(); private readonly IUserAuthSessionService _authSessionService = new UserAuthSessionService(); private readonly IUserAuthOperateService _userAuthOperateService = new UserAuthOperateService(); private const string AppInfo = "AppInfo"; private const string SessionKey = "SessionKey"; private const string SessionUserName = "SessionUserName"; //默认登录界面 public ActionResult Index(string appKey = "", string username = "") { TempData[AppInfo] = _appInfoService.Get(appKey); var viewModel = new PassportLoginRequest { AppKey = appKey, UserName = username }; return View(viewModel); } //授权登录 [HttpPost] public ActionResult Index(PassportLoginRequest model) { //获取应用信息 var appInfo = _appInfoService.Get(model.AppKey); if (appInfo == null) { //应用不存在 return View(model); } TempData[AppInfo] = appInfo; if (ModelState.IsValid == false) { //实体验证失败 return View(model); } //过滤字段无效字符 model.Trim(); //获取用户信息 var userInfo = _appUserService.Get(model.UserName); if (userInfo == null) { //用户不存在 return View(model); } if (userInfo.UserPwd != model.Password.ToMd5()) { //密码不正确 return View(model); } //获取当前未到期的Session var currentSession = _authSessionService.ExistsByValid(appInfo.AppKey, userInfo.UserName); if (currentSession == null) { //构建Session currentSession = new UserAuthSession { AppKey = appInfo.AppKey, CreateTime = DateTime.Now, InvalidTime = DateTime.Now.AddYears(1), IpAddress = Request.UserHostAddress, SessionKey = Guid.NewGuid().ToString().ToMd5(), UserName = userInfo.UserName }; //创建Session _authSessionService.Create(currentSession); } else { //延长有效期,默认一年 _authSessionService.ExtendValid(currentSession.SessionKey); } //记录用户授权日志 _userAuthOperateService.Create(new UserAuthOperate { CreateTime = DateTime.Now, IpAddress = Request.UserHostAddress, Remark = string.Format("{0} 登录 {1} 授权成功", currentSession.UserName, appInfo.Title), SessionKey = currentSession.SessionKey }); 104 var redirectUrl = string.Format("{0}?SessionKey={1}&SessionUserName={2}", appInfo.ReturnUrl, currentSession.SessionKey, userInfo.UserName); //跳转默认回调页面 return Redirect(redirectUrl); } } Memcached会话标识验证核心代码: public class PassportController : ApiController { private readonly IUserAuthSessionService _authSessionService = new UserAuthSessionService(); private readonly IUserAuthOperateService _userAuthOperateService = new UserAuthOperateService(); public bool Get(string sessionKey = "", string remark = "") { if (_authSessionService.GetCache(sessionKey)) { _userAuthOperateService.Create(new UserAuthOperate { CreateTime = DateTime.Now, IpAddress = Request.RequestUri.Host, Remark = string.Format("验证成功-{0}", remark), SessionKey = sessionKey }); return true; } _userAuthOperateService.Create(new UserAuthOperate { CreateTime = DateTime.Now, IpAddress = Request.RequestUri.Host, Remark = string.Format("验证失败-{0}", remark), SessionKey = sessionKey }); return false; } }
Client Authorization Verification Filters Attribute
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)); } }
Example SSO verification attribute usage:
[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(); } }
Summary:
From the draft sample code, we can see that there are many optimizations in code performance, as well as SSO application authorization login A series of prompt messages such as the user account on the page does not exist, the password is incorrect, etc. In the later stage when the business code is running basically correctly, you can consider optimizing more security levels, such as enabling AppSecret private key signature verification, IP range verification, fixed session request attack, and verification code
of the SSO authorization login interface. , Automatic reconstruction of session cache, SSo server, horizontal expansion of cache, etc.The above is the detailed content of Detailed explanation of ASP.NET MVC SSO single sign-on design example. For more information, please follow other related articles on the PHP Chinese website!

iPhone16系列将在全线型号也采用堆叠式后置感光元件设计。该设计在今年的iPhone15标准版上已有类似的应用。今年的标准版iPhone15和iPhone15Plus预期将配备一个4800万像素的后置镜头,并使用能够捕捉更多光线的堆叠式CMOS影像感光元件(CIS)设计。新感光元件设计的产能问题,导致苹果无法在所有iPhone15型号上全面采用此设计。尽管索尼的高端CIS产能预期将在2024年前持续紧张,但Apple已提前确保了大部分的Sony订单。根据郭明錤的说法,索尼产能紧张,将对竞争对

在线投票系统的设计与实现随着互联网的不断发展,在线投票系统成为了一种非常方便和高效的方式来进行民意调查和选举。本文将介绍在线投票系统的设计和实现,并附带一些代码示例。一、系统设计功能需求分析在线投票系统主要具备以下功能:用户注册与登录:用户可以通过注册账号并登录系统来参与投票活动。创建投票:管理员可以创建投票并设定投票的相关参数,如投票主题、选项内容和投票截

随着互联网技术的发展,RESTful风格的API设计成为了最为流行的一种设计方式。而Java作为一种主要的编程语言,也越来越多地在RESTful接口的开发中扮演着重要的角色。在JavaAPI开发中,如何设计出优秀的RESTful接口,成为了一个需要我们深入思考的问题。RESTful接口的基本原则首先,我们需要了解RESTful接口的基本原则。REST即Re

随着互联网技术的不断发展,面向服务架构(SOA)的理念越来越受到人们的重视。在这个背景下,Go语言作为一种高效、可靠的编程语言,也逐渐成为了很多企业与开发者实现SOA的首选语言。本文将深入探讨Go语言中的面向服务架构设计。一、SOA简介面向服务架构是一种软件设计的架构风格,它将复杂的系统拆分成多个相互独立、可复用的服务,每个服务都有独立的功能实现,并使用标准

随着智能车辆在网联化、智能化及架构技术的发展,汽车无论是在固件还是软件上都已经不可逆转的需要进行软件迭代升级。要求在汽车生命周期内会不断的基于汽车OTA能力为整车提供软件升级、固件升级、售后服务等服务能力,可以说,汽车的智能化更迭对于OTA升级能力已经成为不可或缺的主流趋势。本文章将针对自动驾驶汽车的软件升级现状需求及监管要求等进行详细的描述。意在帮助读者整体了解自动驾驶中的软件升级过程原理、准入要求及其应对策略。1整车软件升级技术优势首先,软件定义汽车推动了整车软件升级技术的发展与应用,通过整

RESTfulAPI是目前Web架构中较为常用的一种API设计风格,它的设计理念是基于HTTP协议的标准方法来完成Web资源的表示与交互。在实现过程中,RESTfulAPI遵循一系列规则和约束,包括可缓存、服务器-客户端分离、无状态性等,这些规则保证了API的可维护性、扩展性、安全性以及易用性。接下来,本文将详细介绍RESTfulAPI的设计及其实现方

在互联网时代,文章阅读与分享已经成为人们日常生活中必不可少的一部分。然而,对于文章的点赞与收藏功能来说,用户体验体现的非常关键。而Redis作为一个高性能的键值存储数据库,在文章点赞与收藏功能的实现中有很大的优势。本文将分享一个基于Redis实现的文章点赞功能设计。功能设计文章点赞功能的设计过程中,需要考虑到许多因素。首先,需要将点赞接口暴露给用户,用户可随

如何使用Go语言进行代码安全性设计在当今互联网时代,代码安全性是一项至关重要的任务。无论是为了保护用户的隐私还是避免遭受黑客攻击,代码安全性都是必不可少的。Go语言作为一种现代化的编程语言,提供了许多功能和工具,可以帮助我们进行代码安全性设计。本文将介绍一些在Go语言中实现代码安全性的最佳实践,并提供相应的代码示例。输入验证输入验证是代码安全性的第一道防线。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
