. NET solution for Single sign-on SSO based on Redis cache

Source: Internet
Author: User
Tags httpcontext redis server

First, the basic concept

Recently the company's multiple business systems to unify the use of the same login, this is our familiar single sign-on, the net based on the Redis cache implementation of single sign-on to do a simple sharing.

Single Sign-on, or SSO, is one of the most popular solutions for enterprise business integration at the moment. The definition of SSO is that in multiple application systems, users can access all trusted applications with only one login.

The normal login is written to the session, each time to get a session to see if there is a login to record the user's login status.

Similarly, multiple sites with a credential, you can use the distributed session, we can use Redis implementation of the distributed session, to achieve a simple unified login Demo

We build three sites in local IIS

http://www.a.com Site for login verification

Http://test1.a.com Site 1

Http://test2.a.com Site 2

Modify the host file under C:\Windows\System32\drivers\etc

127.0.0.1 www.a.com

127.0.0.1 test1.a.com

127.0.0.1 test2.a.com

127.0.0.1 sso.a.com

The realization principle, when the user first accesses the application system Test1, because has not logged in, will be directed to the authentication system to log in, according to the user provides the login information, the authentication system carries on the authentication, if passes through the verification, should return to the user one authentication credential--ticket When the user accesses another application, it will take the ticket, as the credentials of their own authentication, and the application system will send the ticket to the authentication system for verification after receiving the request, and check the legality of ticket. If verified, the user can access the application system Test2 and application test3 without having to log in again.

Project structure

Second, the Code implementation

Sso.a.com Login Verification Site

<%@ page language= "C #" autoeventwireup= "true" codebehind= "Index.aspx.cs" inherits= "ADJ. Sso. Web.index "%><! DOCTYPE html>

Code:

 Public partial class Index:System.Web.UI.Page {//define property public string Strtip {get; set;}        public string UserName {get; set;}        public string Passwork {get; set;}                protected void Page_Load (object sender, EventArgs e) {if (Page.IsPostBack) {            ValidateUser ();            }}//Login verify private void ValidateUser () {var username = request.form["username"]; if (username.                Equals ("")) {Strtip = "Please enter user name";            Return            } var password = request.form["password"]; if (password.                Equals ("")) {Strtip = "Please enter password";            Return }//Analog login if (username = = "Admin" && password = = "Admin") {Userinf    o userinfo=new userInfo () {UserName = "admin", PassWord = "admin", Info = "Login Emulation"             }; Generate token var token = Guid.NewGuid ().                ToString (); Write token Common.Common.AddCookie ("token", token, Int32.Parse (configurationmanager.appsettings["Timeout"]))                ;                Write credentials Redisclient client = new Redisclient (configurationmanager.appsettings["Redisserver"], 6379); Client.                Set<userinfo> (token, UserInfo); Jump back to the station if (request.querystring["Backurl"]! = null) {Response.Redirect (R Equest. querystring["Backurl"].                Decrypt (), false); } else {Response.Redirect (configurationmanager.appsettings["Defaulturl")                , false);                }} else {Strtip = "username or password is incorrect!";             Return }        }    }

Configuration file:

<appSettings>  <!--SSO Authentication--  <add key= "Userauthurl" value= "http://sso.a.com/"/>  < !--Redis Server-  <add key= "Redisserver" value= "192.168.10.121"/>  <!--expires--  <add key = "Timeout" value= "/>  <!--default Jump site--  <add key=" Defaulturl "value=" http://test1.a.com/"/> </appSettings>

Logout Code:

var tokenvalue = Common.Common.GetCookie ("token"); Common.Common.AddCookie ("token", tokenvalue,-1); HttpContext.Current.Response.Redirect (configurationmanager.appsettings["Defaulturl"]);

Other sites Verify the login code: Passportservice

public class Passportservice {public static string Tokenreplace () {String strhost = Httpcont Ext.            Current.Request.Url.Host;            String strport = HttpContext.Current.Request.Url.Port.ToString ();            String url = String.Format ("http://{0}:{1}{2}", Strhost, Strport, HTTPCONTEXT.CURRENT.REQUEST.RAWURL); url = regex.replace (URL, @ "(\?|            &) token=.* "," ", regexoptions.ignorecase); return configurationmanager.appsettings["Userauthurl"] + "? backurl=" + URL.        Encrypt ();            } public void Run () {var token = Common.Common.GetCookie ("token");            Redisclient client = new Redisclient (configurationmanager.appsettings["Redisserver"], 6379); UserInfo UserInfo = client.            Get<userinfo> (token);                                                                                                                                        if (UserInfo = = null) { Common.Common.AddCooKie ("token", token,-1);            Token error, re-login HttpContext.Current.Response.Redirect (Tokenreplace (), false); } else {Common.Common.AddCookie ("token", token, Int32.Parse (Configurationmanager.app            settings["Timeout"]));            }} public UserInfo GetUserInfo () {var token = Common.Common.GetCookie ("token");            Redisclient client = new Redisclient (configurationmanager.appsettings["Redisserver"], 6379); Return client. Get<userinfo> (token)??        New UserInfo (); }    }
Third, the last look at the

Four, code download

Here only to do a simple implementation, provides a simple idea, the specific use of the time can continue to improve.

Code Download:

Https://yunpan.cn/cPg3yPN4QHhVx (Extract code: 1610)

. NET solution for Single sign-on SSO based on Redis cache

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.