什么是單點登錄?
我想肯定有一部分人“望文生義”的認為單點登錄就是一個用戶只能在一處登錄,其實這是錯誤的理解(我記得我第一次也是這么理解的)。
單點登錄指的是多個子系統只需要登錄一個,其他系統不需要登錄了(一個瀏覽器內)。一個子系統退出,其他子系統也全部是退出狀態。
如果你還是不明白,我們舉個實際的例子把。比如服務器之家首頁: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重定向,并沒有輸入用戶名密碼去登錄。用戶完全感覺不到,直接就是登錄狀態了。
圖解:
手擼一個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(); } |
效果圖:
當然,這只是用較少的代碼擼了一個較簡單的sso。僅用來理解,勿用于實際應用。
identityserver4實現sso
環境:.net core 2.0
上面我們手擼了一個sso,接下來我們看看.net里的identityserver4怎么來使用sso。
首先建一個identityserver4_sso_service(mvc項目),再建兩個identityserver4_sso_client(mvc項目)
在service項目中用nuget導入identityserver4 2.0.2
、identityserver4.aspnetidentity 2.0.0
、identityserver4.entityframework 2.0.0
在client項目中用nuget導入identitymodel 2.14.0
然后分別設置service和client項目啟動端口為 5001(service)、5002(client1)、5003(client2)
在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" ); }); } |
對于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" ); } |
效果圖:
源碼地址(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