Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of .net single sign-on Design

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail the example analysis of .net single sign-on design. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Name definition

To facilitate explanation, first explain the meaning of several nouns that appear in the text:

P station: unified login authorization verification center. The domain name in demo is www.passport.com:801.

Station A: a test website under different domain names. The domain name in demo is www.a.com:802.

Bilibili: test websites under different domain names. The domain name in demo is www.b.com:803.

Token: the secret key for the user to access the P station

Ticket: an encrypted string used to save user information

Single sign-on

If you need to log in to the A station, jump to the P station to log in, and then jump back to the A station after the P station landing. The user visits the page that bilibili needs to log in again, and the user can visit normally without a login operation.

Realization idea

When an unlogged-in user accesses the A station, it will redirect to the authorization center of the P station. The P station first detects the Cookie to determine that it is not currently in the login state, and then jumps to the login page to carry out the login operation. After the login is successful, the encrypted ticket of the user information is attached to the request address of A, and the A station obtains the user information by decrypting the ticket, which is successfully stored in the Session (so that the user is in the login state in A). Access through When the user visits bilibili again, for bilibili, if the user is not logged in, the user will also be redirected to the authorization center of the P station. The P station detects the Cookie and determines that the current user is in the login state. The current user information is encrypted as ticket and attached to the request address of B to return, and the latter operation is the same as that of the A station. In this way, the user information is stored in the Session of An or BMagol An and B after logging in, and the P station will not be requested again.

Simple diagram

Swimming lane flow chart

Main logical explanation

Main logic of station A

The user first visits station A, where a Token is generated and stored in Cache. Token is the key for A to access P, and P needs to carry this Token when calling back to A. A requests Token,P P to verify that Token is called to check whether Token is the sent Token. After verification, Token is invalidated to prevent Token from being used again.

Token is generated by taking different fields of the timestamp for MD5 encryption. Of course, you can add a salt to prevent counterfeiting.

/ public static string CreateToken (DateTime timestamp) {StringBuilder securityKey = new StringBuilder (MD5Encypt (timestamp.ToString ("yyyy")); securityKey.Append (MD5Encypt (timestamp.ToString ("MM")); securityKey.Append (MD5Encypt (timestamp.ToString ("dd"); securityKey.Append (MD5Encypt (timestamp.ToString ("HH") SecurityKey.Append (MD5Encypt (timestamp.ToString ("mm"); securityKey.Append (MD5Encypt (timestamp.ToString ("ss"); return MD5Encypt (securityKey.ToString ());}

When P calls back to A, the Token is verified in A. if the verification is not successful, the unified authorization and verification of the P station is requested.

/ Authorization enumeration / public enum AuthCodeEnum {Public = 1, Login = 2} / Authorization filter / public class AuthAttribute: ActionFilterAttribute {/ permission Code / public AuthCodeEnum Code {get; set } / verify permissions / public override void OnActionExecuting (ActionExecutingContext filterContext) {var request = filterContext.HttpContext.Request; var session = filterContext.HttpContext.Session; / / if identity information exists if (Common.CurrentUser = = null) {if (Code = = AuthCodeEnum.Public) {return } string reqToken = request ["Token"]; string ticket = request ["Ticket"]; Cache cache = HttpContext.Current.Cache; / / No Token was obtained or the Token authentication failed or the ticket failed to get the callback from P TokenModel tokenModel= cache.Get (ConstantHelper.TOKEN_KEY) = = null?null: (TokenModel) cache.Get (ConstantHelper.TOKEN_KEY) If (string.IsNullOrEmpty (reqToken) | | tokenModel = = null | | string.IsNullOrEmpty (ticket)) {DateTime timestamp = DateTime.Now; string returnUrl = request.Url.AbsoluteUri; tokenModel = new TokenModel {TimeStamp = timestamp, Token = AuthernUtil.CreateToken (timestamp)} / / Token is added to the cache with a design expiration time of 20 minutes cache.Add (ConstantHelper.TOKEN_KEY, tokenModel, null, DateTime.Now.AddMinutes (20), Cache.NoSlidingExpiration,CacheItemPriority.Default, null); filterContext.Result = new ContentResult {Content = GetAuthernScript (AuthernUtil.GetAutherUrl (tokenModel.Token, timestamp), returnUrl)}; return } LoginService service = new LoginService (); var userinfo = service.GetUserInfo (ticket); session [ConstantHelper. User _ SESSION_KEY] = userinfo; / / Verification passed. Remove Token from cache to ensure that cache.Remove (ConstantHelper.TOKEN_KEY) can only be used once per token. }} / generate a redirect script / callback address / private string GetAuthernScript (string authernUrl, string returnUrl) {StringBuilder sbScript = new StringBuilder (); sbScript.Append ("); sbScript.AppendFormat (" _ window.location.href=' {0} & returnUrl=' + encodeURIComponent ('{1}')) ", authernUrl, returnUrl); sbScript.Append ("); return sbScript.ToString ();}}

Code description: here to facilitate the setting of the expiration time of Token, so use Cache to access Token, set the expiration time of Token to two minutes, and remove Token from cache when the verification is successful.

Call filter

[Auth (Code = AuthCodeEnum.Login)] public ActionResult Index () {return View ();}

P station main logic

P station receives the authorization request, P station first uses Coookie to determine whether to log in, and if it does not log in, it jumps to the landing page for landing operation.

/ Authorization login verification / [HttpPost] public ActionResult PassportVertify () {var cookie= request. Cookies [ConstantHelper.user _ COOKIE_KEY]; if (cookie= = null | | string.IsNullOrEmpty (cookie.ToString () {return RedirectToAction ("Login", new {ReturnUrl = Request ["ReturnUrl"], Token= Request ["Token"]}) } string userinfo = cookie.ToString (); var success= passportservice.AuthernVertify (Request ["Token"], Convert.ToDateTime (Request ["TimeStamp"]); if (! success) {return RedirectToAction ("Login", new {ReturnUrl = Request ["ReturnUrl"], Token = Request ["Token"]});} return Redirect (passportservice.GetReturnUrl (userinfo, Request ["Token"], Request ["ReturnUrl"]));}

Verify Token if you have logged in

/ verify token / token / / timestamp / public bool AuthernVertify (string token,DateTime timestamp) {return AuthernUtil.CreateToken (timestamp) = = token;}

Test description

1. Modify host

127.0.0.1 www.passport.com

127.0.0.1 www.a.com

127.0.0.1 www.b.com

2. Deploy IIS

P www.passport.com:801

A www.a.com:802

B www.b.com:803

3. Test account and webconfig

User name: admin password: 123

This is the end of the sample analysis of. Net single sign-on design. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report