深入淺析C#中單點登錄的原理和使用
什么是單點登錄?
我想肯定有一部分人“望文生義”的認為單點登錄就是一個用戶只能在一處登錄,其實這是錯誤的理解(我記得我第一次也是這么理解的)。
單點登錄指的是多個子系統(tǒng)只需要登錄一個,其他系統(tǒng)不需要登錄了(一個瀏覽器內(nèi))。一個子系統(tǒng)退出,其他子系統(tǒng)也全部是退出狀態(tài)。
如果你還是不明白,我們舉個實際的例子把。比如腳本之家首頁:https://www.jb51.ne ,和腳本之家的搜索http://so.jb51.net 。這就是兩個系統(tǒng)(不同的域名)。如果你登錄其中一個,另一個也是登錄狀態(tài)。如果你退出一個,另一個也是退出狀態(tài)了。
那么這是怎么實現(xiàn)的呢?這就是我們今天要分析的問題了。
單點登錄(SSO)原理
首先我們需要一個認證中心(Service),和兩個子系統(tǒng)(Client)。
當瀏覽器第一次訪問Client1時,處于未登錄狀態(tài) -> 302到認證中心(Service) -> 在Service的登錄頁面登錄(寫入Cookie記錄登錄信息) -> 302到Client1(寫入Cookie記錄登錄信息)第二次訪問Client1 -> 讀取Client1中Cookie登錄信息 -> Client1為登錄狀態(tài)
第一次訪問Client2 -> 讀取Client2中Cookie中的登錄信息 -> Client2為未登錄狀態(tài) -> 302到在Service(讀取Service中的Cookie為登錄狀態(tài)) -> 302到Client2(寫入Cookie記錄登錄信息)
我們發(fā)現(xiàn)在訪問Client2的時候,中間時間經(jīng)過了幾次302重定向,并沒有輸入用戶名密碼去登錄。用戶完全感覺不到,直接就是登錄狀態(tài)了。
圖解:

手擼一個SSO
環(huán)境:.NET Framework 4.5.2
Service:
/// <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標識會話是登錄狀態(tài)
Session["user"] = "XX已經(jīng)登錄";
//在認證中心 保存客戶端Client的登錄認證碼
TokenIds.Add(Session.SessionID, Guid.NewGuid());
}
else//驗證失敗重新登錄
{
return "/Home/Login";
}
return backUrl + "?tokenId=" + TokenIds[Session.SessionID];//生成一個tokenId 發(fā)放到客戶端
}
Client:
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 (主要是為了可以統(tǒng)一登出)
Tokens.Add(tokenId);
}
Session["token"] = tokenId;
}
}
}
//判斷是否是登錄狀態(tài)
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。僅用來理解,勿用于實際應(yīng)用。
IdentityServer4實現(xiàn)SSO
環(huán)境:.NET Core 2.0
上面我們手擼了一個SSO,接下來我們看看.NET里的IdentityServer4怎么來使用SSO。
首先建一個IdentityServer4_SSO_Service(MVC項目),再建兩個IdentityServer4_SSO_Client(MVC項目)
在Service項目中用nuget導(dǎo)入IdentityServer4 2.0.2、IdentityServer4.AspNetIdentity 2.0.0、IdentityServer4.EntityFramework 2.0.0
在Client項目中用nuget導(dǎo)入IdentityModel 2.14.0
然后分別設(shè)置Service和Client項目啟動端口為 5001(Service)、5002(Client1)、5003(Client2)

在Service中新建一個類Config:
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:
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
在文件appsettings.json中配置數(shù)據(jù)庫連接字符串:
"ConnectionStrings": {
"DefaultConnection": "Server=(local);Database=IdentityServer4_Demo;Trusted_Connection=True;MultipleActiveResultSets=true"
}
在文件Startup.cs的ConfigureServices方法中增加:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); //數(shù)據(jù)庫連接字符串
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(初始化數(shù)據(jù)庫):
/// <summary>
/// 初始數(shù)據(jù)庫
/// </summary>
/// <param name="app"></param>
private void InitializeDatabase(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();//執(zhí)行數(shù)據(jù)庫遷移
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())//循環(huán)添加 我們直接添加的 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方法:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//初始化數(shù)據(jù)
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控制器,分別實現(xiàn)注冊、登錄、登出等。
新建一個ConsentController控制器用于Client回調(diào)。
然后在Client的Startup.cs類里修改ConfigureServices方法:
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的身份認證就簡單了:
[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可配置數(shù)據(jù)庫連接后直接運行)
https://github.com/zhaopeiym/BlogDemoCode/tree/master/sso(%E5%8D%95%E7%82%B9%E7%99%BB%E5%BD%95)
總結(jié)
以上所述是小編給大家介紹的C#中單點登錄的原理和使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
C#實現(xiàn)軟件開機自啟動功能(不需要管理員權(quán)限)
在本文中,我們探討了如何使用C#語言實現(xiàn)應(yīng)用程序在系統(tǒng)啟動時自動運行的功能,同時避免了對管理員權(quán)限的需求,文章通過代碼示例講解的非常詳細,對大家的學(xué)習或工作有一定的幫助,需要的朋友可以參考下2025-04-04
C#/VB.NET實現(xiàn)在PDF文檔中創(chuàng)建表格
表格是一種直觀高效的數(shù)據(jù)展示方式,可以按行和列的形式呈現(xiàn)數(shù)據(jù),從而更容易吸引讀者的注意,本文將介紹如何使用 Spire.PDF for .NET 通過 .NET 程序在 PDF 文檔中創(chuàng)建表格,需要的可以參考下2023-12-12

