.NET基於Redis緩存實現單點登錄SSO的解決方案


一、基本概念

最近公司的多個業務系統要統一整合使用同一個登錄,這就是我們耳熟能詳的單點登錄,現在就NET基於Redis緩存實現單點登錄做一個簡單的分享。

單點登錄(Single Sign On),簡稱為 SSO,是目前比較流行的企業業務整合的解決方案之一。SSO的定義是在多個應用系統中,用戶只需要登錄一次就可以訪問所有相互信任的應用系統。

普通的登錄是寫入session,每次獲取session看看是否有登錄就可記錄用戶的登錄狀態。

同理多個站點用一個憑證,可以用分布式session,我們可以用redis實現分布式session,來實現一個簡單的統一登錄demo

我們在本地IIS建立三個站點

http://www.a.com  登錄驗證的站點

http://test1.a.com 站點1

http://test2.a.com 站點2

修改host文件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

具體實現原理,當用戶第一次訪問應用系統test1的時候,因為還沒有登錄,會被引導到認證系統中進行登錄;根據用戶提供的登錄信息,認證系統進行身份校驗,如果通過校驗,應該返回給用戶一個認證的憑據--ticket;用戶再訪問別的應用的時候就會將這個ticket帶上,作為自己認證的憑據,應用系統接受到請求之后會把ticket送到認證系統進行校驗,檢查ticket的合法性。如果通過校驗,用戶就可以在不用再次登錄的情況下訪問應用系統test2和應用系統test3了。

項目結構

二、代碼實現

sso.a.com登錄驗證站點

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="ADJ.SSO.Web.Index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>SSO demo</title>
</head>
<body>
    <form id="form1" runat="server">
           用  戶:<input id="txtUserName" type="text" name="userName" /><br /><br />
           密  碼:<input type="password" name="passWord" /><br /><br />
            <input type="submit" value="登錄" /><br /><br />
         
            <span style="color: red; margin-top: 20px;"><%=StrTip %></span>
    </form>

</body>
</html>

代碼:

 public partial class Index : System.Web.UI.Page
    {
        //定義屬性
        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();
            }
        }

        //登錄驗證
        private void ValidateUser()
        {
            var username = Request.Form["userName"];
            if (username.Equals(""))
            {
                StrTip = "請輸入用戶名";
                return;
            }
            var password = Request.Form["passWord"];
            if (password.Equals(""))
            {
                StrTip = "請輸入密碼";
                return;
            }

            //模擬登錄
            if (username == "admin" && password == "admin")
            {
                UserInfo userInfo=new UserInfo()
                {
                    UserName = "admin",PassWord = "admin",Info ="登錄模擬" 
                };

                //生成token
                var token = Guid.NewGuid().ToString();
                //寫入token
                Common.Common.AddCookie("token", token, Int32.Parse(ConfigurationManager.AppSettings["Timeout"]));
                //寫入憑證
                RedisClient client = new RedisClient(ConfigurationManager.AppSettings["RedisServer"], 6379);
                client.Set<UserInfo>(token, userInfo);


                //跳轉回分站
                if (Request.QueryString["backurl"] != null)
                {
                    Response.Redirect(Request.QueryString["backurl"].Decrypt(), false);
                }
                else
                {
                    Response.Redirect(ConfigurationManager.AppSettings["DefaultUrl"], false);
                }
            }
            else
            {
                StrTip = "用戶名或密碼有誤!";
                return; 
            }

        }
    }

配置文件:

<appSettings>
  <!--sso驗證-->
  <add key="UserAuthUrl" value="http://sso.a.com/"/>
  <!--redis服務器-->
  <add key="RedisServer" value="192.168.10.121"/>
  <!--過期時間-->
  <add key="Timeout" value="30"/>
  <!--默認跳轉站點-->
  <add key="DefaultUrl" value="http://test1.a.com/"/>
</appSettings>

注銷代碼:

var tokenValue = Common.Common.GetCookie("token");
Common.Common.AddCookie("token",tokenValue,-1);
HttpContext.Current.Response.Redirect(ConfigurationManager.AppSettings["DefaultUrl"]);

其他站點驗證是否登錄的代碼:PassportService

public class PassportService
    {
        public static string TokenReplace()
        {
            string strHost = HttpContext.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);
                //令牌錯誤,重新登錄
                HttpContext.Current.Response.Redirect(TokenReplace(), false);
            }
            else
            {
                Common.Common.AddCookie("token", token, Int32.Parse(ConfigurationManager.AppSettings["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();
        }

    }

三、最后看下效果圖

四、代碼下載

這里只做了一個簡單的實現,提供了一個簡單的思路,具體用的時候可以繼續完善。

代碼下載:

http://pan.baidu.com/s/1pK9U8Oj

 

五、加關注

如果本文對你有幫助,請點擊右下角【好文要頂】和【關注我

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM