一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - C# - 深入淺析C#中單點登錄的原理和使用

深入淺析C#中單點登錄的原理和使用

2022-01-25 14:14農碼一生 C#

這篇文章主要介紹了C#中單點登錄的原理和使用,需要的朋友可以參考下

什么是單點登錄?

我想肯定有一部分人“望文生義”的認為單點登錄就是一個用戶只能在一處登錄,其實這是錯誤的理解(我記得我第一次也是這么理解的)。

單點登錄指的是多個子系統只需要登錄一個,其他系統不需要登錄了(一個瀏覽器內)。一個子系統退出,其他子系統也全部是退出狀態。

如果你還是不明白,我們舉個實際的例子把。比如服務器之家首頁:http://www.ythuaji.com.cn ,和服務器之家的工具https://tool.zzvips.com 。這就是兩個系統(不同的域名)。如果你登錄其中一個,另一個也是登錄狀態。如果你退出一個,另一個也是退出狀態了。

那么這是怎么實現的呢?這就是我們今天要分析的問題了。

單點登錄(sso)原理

首先我們需要一個認證中心(service),和兩個子系統(client)。

當瀏覽器第一次訪問client1時,處于未登錄狀態 -> 302到認證中心(service) -> 在service的登錄頁面登錄(寫入cookie記錄登錄信息) -> 302到client1(寫入cookie記錄登錄信息)第二次訪問client1 -> 讀取client1中cookie登錄信息 -> client1為登錄狀態

第一次訪問client2 -> 讀取client2中cookie中的登錄信息 -> client2為未登錄狀態 -> 302到在service(讀取service中的cookie為登錄狀態) -> 302到client2(寫入cookie記錄登錄信息)

我們發現在訪問client2的時候,中間時間經過了幾次302重定向,并沒有輸入用戶名密碼去登錄。用戶完全感覺不到,直接就是登錄狀態了。

圖解:


深入淺析C#中單點登錄的原理和使用

手擼一個sso

環境:.net framework 4.5.2

service:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/// <summary>
/// 登錄
/// </summary>
/// <param name="name"></param>
/// <param name="password"></param>
/// <param name="backurl"></param>
/// <returns></returns>
[httppost]
public string login(string name, string password, string backurl)
{
 if (true)//todo:驗證用戶名密碼登錄
 {
  //用session標識會話是登錄狀態
  session["user"] = "xx已經登錄";
  //在認證中心 保存客戶端client的登錄認證碼
  tokenids.add(session.sessionid, guid.newguid());
 }
 else//驗證失敗重新登錄
 {
  return "/home/login";
 }
 return backurl + "?tokenid=" + tokenids[session.sessionid];//生成一個tokenid 發放到客戶端
}

client:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public static list<string> tokens = new list<string>();
public async task<actionresult> index()
{
 var tokenid = request.querystring["tokenid"];
 //如果tokenid不為空,則是由service302過來的。
 if (tokenid != null)
 {
  using (httpclient http = new httpclient())
  {
   //驗證tokend是否有效
   var isvalid = await http.getstringasync("http://localhost:8018/home/tokenidisvalid?tokenid=" + tokenid);
   if (bool.parse(isvalid.tostring()))
   {
    if (!tokens.contains(tokenid))
    {
     //記錄登錄過的client (主要是為了可以統一登出)
     tokens.add(tokenid);
    }
    session["token"] = tokenid;
   }
  }
 }
 //判斷是否是登錄狀態
 if (session["token"] == null || !tokens.contains(session["token"].tostring()))
 {
  return redirect("http://localhost:8018/home/verification?backurl=http://localhost:26756/home");
 }
 else
 {
  if (session["token"] != null)
   session["token"] = null;
 }
 return view();
}

效果圖:


深入淺析C#中單點登錄的原理和使用

當然,這只是用較少的代碼擼了一個較簡單的sso。僅用來理解,勿用于實際應用。

identityserver4實現sso

環境:.net core 2.0

上面我們手擼了一個sso,接下來我們看看.net里的identityserver4怎么來使用sso。

首先建一個identityserver4_sso_service(mvc項目),再建兩個identityserver4_sso_client(mvc項目)
在service項目中用nuget導入identityserver4 2.0.2identityserver4.aspnetidentity 2.0.0identityserver4.entityframework 2.0.0
在client項目中用nuget導入identitymodel 2.14.0

然后分別設置service和client項目啟動端口為 5001(service)、5002(client1)、5003(client2)


深入淺析C#中單點登錄的原理和使用
在service中新建一個類config:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
public class config
 public static ienumerable<identityresource> getidentityresources()
  {
   return new list<identityresource>
   {
    new identityresources.openid(),
    new identityresources.profile(),
   };
  }
 public static ienumerable<apiresource> getapiresources()
 {
  return new list<apiresource>
  {
   new apiresource("api1", "my api")
  };
 }
 // 可以訪問的客戶端
 public static ienumerable<client> getclients()
  {  
   return new list<client>
   {   
    // openid connect hybrid flow and client credentials client (mvc)
    //client1
    new client
    {
     clientid = "mvc1",
     clientname = "mvc client1",
     allowedgranttypes = granttypes.hybridandclientcredentials,
     requireconsent = true,
     clientsecrets =
     {
      new secret("secret".sha256())
     },
     redirecturis = { "http://localhost:5002/signin-oidc" }, //注意端口5002 是我們修改的client的端口
     postlogoutredirecturis = { "http://localhost:5002/signout-callback-oidc" },
     allowedscopes =
     {
      identityserverconstants.standardscopes.openid,
      identityserverconstants.standardscopes.profile,
      "api1"
     },
     allowofflineaccess = true
    },
     //client2
    new client
    {
     clientid = "mvc2",
     clientname = "mvc client2",
     allowedgranttypes = granttypes.hybridandclientcredentials,
     requireconsent = true,
     clientsecrets =
     {
      new secret("secret".sha256())
     },
     redirecturis = { "http://localhost:5003/signin-oidc" },
     postlogoutredirecturis = { "http://localhost:5003/signout-callback-oidc" },
     allowedscopes =
     {
      identityserverconstants.standardscopes.openid,
      identityserverconstants.standardscopes.profile,
      "api1"
     },
     allowofflineaccess = true
    }
   };
  }
}

新增一個applicationdbcontext類繼承于identitydbcontext:

?
1
2
3
4
5
6
7
8
9
10
11
public class applicationdbcontext : identitydbcontext<identityuser>
{
 public applicationdbcontext(dbcontextoptions<applicationdbcontext> options)
  : base(options)
 {
 }
 protected override void onmodelcreating(modelbuilder builder)
 {
  base.onmodelcreating(builder);
 }
}

在文件appsettings.json中配置數據庫連接字符串:

?
1
2
3
"connectionstrings": {
 "defaultconnection": "server=(local);database=identityserver4_demo;trusted_connection=true;multipleactiveresultsets=true"
 }

在文件startup.cs的configureservices方法中增加:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public void configureservices(iservicecollection services)
{
 services.adddbcontext<applicationdbcontext>(options =>
  options.usesqlserver(configuration.getconnectionstring("defaultconnection"))); //數據庫連接字符串
 services.addidentity<identityuser, identityrole>()
  .addentityframeworkstores<applicationdbcontext>()
  .adddefaulttokenproviders();
 services.addmvc();
 string connectionstring = configuration.getconnectionstring("defaultconnection");
 var migrationsassembly = typeof(startup).gettypeinfo().assembly.getname().name;
 services.addidentityserver()
  .adddevelopersigningcredential()
  .addaspnetidentity<identityuser>()
  .addconfigurationstore(options =>
  {
   options.configuredbcontext = builder =>
    builder.usesqlserver(connectionstring,
     sql => sql.migrationsassembly(migrationsassembly));
  })
  .addoperationalstore(options =>
  {
   options.configuredbcontext = builder =>
    builder.usesqlserver(connectionstring,
     sql => sql.migrationsassembly(migrationsassembly));
   options.enabletokencleanup = true;
   options.tokencleanupinterval = 30;
  });
}

并在startup.cs文件里新增一個方法initializedatabase(初始化數據庫):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/// <summary>
/// 初始數據庫
/// </summary>
/// <param name="app"></param>
private void initializedatabase(iapplicationbuilder app)
{
 using (var servicescope = app.applicationservices.getservice<iservicescopefactory>().createscope())
 {
  servicescope.serviceprovider.getrequiredservice<applicationdbcontext>().database.migrate();//執行數據庫遷移
  servicescope.serviceprovider.getrequiredservice<persistedgrantdbcontext>().database.migrate();
  var context = servicescope.serviceprovider.getrequiredservice<configurationdbcontext>();
  context.database.migrate();
  if (!context.clients.any())
  {
   foreach (var client in config.getclients())//循環添加 我們直接添加的 5002、5003 客戶端
   {
    context.clients.add(client.toentity());
   }
   context.savechanges();
  }
  if (!context.identityresources.any())
    {
     foreach (var resource in config.getidentityresources())
     {
      context.identityresources.add(resource.toentity());
     }
     context.savechanges();
    }
  if (!context.apiresources.any())
    {
     foreach (var resource in config.getapiresources())
     {
      context.apiresources.add(resource.toentity());
     }
     context.savechanges();
    }
 }
}

修改configure方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void configure(iapplicationbuilder app, ihostingenvironment env)
{
 //初始化數據
 initializedatabase(app);
 if (env.isdevelopment())
 {
  app.usedeveloperexceptionpage();
  app.usebrowserlink();
  app.usedatabaseerrorpage();
 }
 else
 {
  app.useexceptionhandler("/home/error");
 }
 app.usestaticfiles();
 app.useidentityserver();
 app.usemvc(routes =>
 {
  routes.maproute(
   name: "default",
   template: "{controller=home}/{action=index}/{id?}");
 });
}

然后新建一個accountcontroller控制器,分別實現注冊、登錄、登出等。

新建一個consentcontroller控制器用于client回調。

然后在client的startup.cs類里修改configureservices方法:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void configureservices(iservicecollection services)
{
 services.addmvc();
 jwtsecuritytokenhandler.defaultinboundclaimtypemap.clear();
 services.addauthentication(options =>
 {
  options.defaultscheme = "cookies";
  options.defaultchallengescheme = "oidc";
 }).addcookie("cookies").addopenidconnect("oidc", options =>
 {
  options.signinscheme = "cookies";
  options.authority = "http://localhost:5001";
  options.requirehttpsmetadata = false;
  options.clientid = "mvc2";
  options.clientsecret = "secret";
  options.responsetype = "code id_token";
  options.savetokens = true;
  options.getclaimsfromuserinfoendpoint = true;
  options.scope.add("api1");
  options.scope.add("offline_access");
 });
}

深入淺析C#中單點登錄的原理和使用

對于client的身份認證就簡單了:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[authorize]//身份認證
public iactionresult index()
{
 return view();
}
 
/// <summary>
/// 登出
/// </summary>
/// <returns></returns>
public async task<iactionresult> logout()
{
 await httpcontext.signoutasync("cookies");
 await httpcontext.signoutasync("oidc");
 return view("index");
}

效果圖:


深入淺析C#中單點登錄的原理和使用

源碼地址(demo可配置數據庫連接后直接運行)

https://github.com/zhaopeiym/blogdemocode/tree/master/sso(%e5%8d%95%e7%82%b9%e7%99%bb%e5%bd%95)

總結

以上所述是小編給大家介紹的c#中單點登錄的原理和使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!

原文鏈接:http://www.cnblogs.com/zhaopei/p/SSO.html

延伸 · 閱讀

精彩推薦
  • C#C# 實現對PPT文檔加密、解密及重置密碼的操作方法

    C# 實現對PPT文檔加密、解密及重置密碼的操作方法

    這篇文章主要介紹了C# 實現對PPT文檔加密、解密及重置密碼的操作方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下...

    E-iceblue5012022-02-12
  • C#C#實現XML文件讀取

    C#實現XML文件讀取

    這篇文章主要為大家詳細介紹了C#實現XML文件讀取的相關代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下...

    Just_for_Myself6702022-02-22
  • C#WPF 自定義雷達圖開發實例教程

    WPF 自定義雷達圖開發實例教程

    這篇文章主要介紹了WPF 自定義雷達圖開發實例教程,本文介紹的非常詳細,具有參考借鑒價值,需要的朋友可以參考下...

    WinterFish13112021-12-06
  • C#C#設計模式之Visitor訪問者模式解決長隆歡樂世界問題實例

    C#設計模式之Visitor訪問者模式解決長隆歡樂世界問題實例

    這篇文章主要介紹了C#設計模式之Visitor訪問者模式解決長隆歡樂世界問題,簡單描述了訪問者模式的定義并結合具體實例形式分析了C#使用訪問者模式解決長...

    GhostRider9502022-01-21
  • C#C#通過KD樹進行距離最近點的查找

    C#通過KD樹進行距離最近點的查找

    這篇文章主要為大家詳細介紹了C#通過KD樹進行距離最近點的查找,具有一定的參考價值,感興趣的小伙伴們可以參考一下...

    帆帆帆6112022-01-22
  • C#深入解析C#中的交錯數組與隱式類型的數組

    深入解析C#中的交錯數組與隱式類型的數組

    這篇文章主要介紹了深入解析C#中的交錯數組與隱式類型的數組,隱式類型的數組通常與匿名類型以及對象初始值設定項和集合初始值設定項一起使用,需要的...

    C#教程網6172021-11-09
  • C#Unity3D實現虛擬按鈕控制人物移動效果

    Unity3D實現虛擬按鈕控制人物移動效果

    這篇文章主要為大家詳細介紹了Unity3D實現虛擬按鈕控制人物移動效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一...

    shenqingyu060520232410972022-03-11
  • C#C#裁剪,縮放,清晰度,水印處理操作示例

    C#裁剪,縮放,清晰度,水印處理操作示例

    這篇文章主要為大家詳細介紹了C#裁剪,縮放,清晰度,水印處理操作示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下...

    吳 劍8332021-12-08
主站蜘蛛池模板: 久9青青cao精品视频在线 | 国产草草视频 | 99久久成人| 男人j放进女人的p视频免费 | 免费看成年视频网页 | 黄色a站| 涩涩国产精品福利在线观看 | 色综合久久夜色精品国产 | 91探花在线观看 | 甜宠巨肉h文1v1校园 | 国产成人精品一区二区不卡 | 国产在线步兵一区二区三区 | 国产经典一区二区三区蜜芽 | 午夜福利理论片高清在线 | 久久理论片迅播影院一级 | 关晓彤被草 | 欧亚精品一区二区三区 | 亚洲国产精品热久久 | aaa一级最新毛片 | 99精品国产综合久久久久 | 午色影院| 91在线 一区 二区三区 | 不知火舞被c视频在线播放 不卡一区二区三区卡 | japanese人妖xvideos | 日本黄视频在线播放 | bbc japanese黑人强行 | 久久久久久久久人体 | 和两个男人玩3p好爽视频 | 久久成人亚洲 | 无码人妻精品一区二区蜜桃在线看 | h版欧美大片免费观看 | 深夜视频在线播放 | hd性欧美俱乐部中文 | 四虎影视最新 | 成人精品网 | 精品伊人| 青柠在线完整高清观看免费 | 黄片毛片 | 国产伦精品一区二区三区免 | 欧美视频黑鬼大战白妞 | 1313午夜精品久久午夜片 |