浅析C#中单点登录的原理和使用
是单点登录?
我想肯定有一部分人“望文生义”的认为单点登录就是一个用户只能在一处登录,其实这是错误的理解(我记得我第一次也是这么理解的)。
单点登录指的是多个子系统只需要登录一个,其他系统不需要登录了(一个浏览器内)。一个子系统退出,其他子系统也全部是退出状态。
如果你还是不明白,我们举个实际的例子把。比如博客园首页:https://www.cnblogs.com,和博客园的找找看http://zzk.cnblogs.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:
/// <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:
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:
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)//Client1new 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}, //Client2new 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中配置数据库连接字符串:
"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"))); //数据库连接字符串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(初始化数据库):
/// <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方法:
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方法:
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可配置数据库连接后直接运行)
https://github.com/zhaopeiym/BlogDemoCode/tree/master/sso(%E5%8D%95%E7%82%B9%E7%99%BB%E5%BD%95)
推荐阅读
http://www.cnblogs.com/ywlaker/p/6113927.html
https://identityserver4.readthedocs.io/en/release
相关文章:
IdentityServer4(OAuth2.0服务)折腾笔记
IdentityServer4 实现 OpenID Connect 和 OAuth 2.0
IdentityServer4 使用OpenID Connect添加用户身份验证
IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架学习保护API
IdentityServer4 指定角色授权(Authorize(Roles="admin"))
IdentityServer4 SigningCredential(RSA 证书加密)
IdentityServer4 实现自定义 GrantType 授权模式
IdentityServer4 配置负载均衡
学习Identity Server 4的预备知识
原文地址:http://www.cnblogs.com/zhaopei/p/SSO.html
.NET社区新闻,深度好文,微信中搜索dotNET跨平台或扫描二维码关注
浅析C#中单点登录的原理和使用相关推荐
- 企业门户应用整合中单点登录(SSO)的技术实现与应用
企业门户应用整合中单点登录(SSO)的技术实现与应用 相关专题: 电子应用 时间:2009-07-27 09:56来源: icbuy亿芯网 1 引 言 企业在信息化建设过程中,由于经常采用逐步信息化的 ...
- 单点登录简单原理(应用多系统)
单点登录原理与简单实现 1.http无状态协议 web应用采用browser/server架构,http作为通信协议.http是无状态协议,浏览器的每一次请求,服务器会独立处理,不与之前或之后的请求 ...
- Oauth2.0实现单点登录的原理流程,这次总该懂了!
单点登录是多域名企业站点流行的登录方式.本文以现实生活场景辅助理解,力争彻底理清 OAuth2.0 实现单点登录的原理流程.同时总结了权限控制的实现方案,及其在微服务架构中的应用. 1 什么是单点登录 ...
- Oauth2.0实现单点登录的原理流程
Oauth2.0实现单点登录的原理流程 1.什么是单点登录 2.OAuth2 认证授权的原理流程 3.基于 SpringBoot 实现认证/授权 4.综合运用 1.什么是单点登录 1.1 多点登录 传 ...
- Oauth2.0实现单点登录的原理流程,通俗易懂
单点登录是多域名企业站点流行的登录方式.本文以现实生活场景辅助理解,力争彻底理清 OAuth2.0 实现单点登录的原理流程.同时总结了权限控制的实现方案,及其在微服务架构中的应用. 1 什么是单点登录 ...
- Oauth2.0实现单点登录的原理流程,通俗易懂!
点击上方☝码猿技术专栏 轻松关注,设为星标! 及时获取有趣有料的技术 单点登录是多域名企业站点流行的登录方式.本文以现实生活场景辅助理解,力争彻底理清 OAuth2.0 实现单点登录的原理流程.同时总 ...
- 单点登录(原理与代码)
文章目录 一.单点登录简介 SSO 原理(单点登录的过程) SSO 实现技术 SSO 常见方案 二.手写单点登录系统架构(代码篇) 三.单点登录详介(原理篇) 1.登录 2.注销 单点登陆的具体实现: ...
- 单点登录系统原理与实现,图文并茂
一.单系统登录机制 1.http无状态协议 web应用采用browser/server架构,http作为通信协议.http是无状态协议,浏览器的每一次请求,服务器会独立处理,不与之前或之后的请求产生关 ...
- CAS 5.2.x 单点登录 - 实现原理及源码浅析
上一篇文章简单介绍了 CAS 5.2.2 在本地开发环境中搭建服务端和客户端,对单点登录过程有了一个直观的认识之后,本篇将探讨 CAS 单点登录的实现原理. 一.Session 和 Cookie HT ...
最新文章
- python 创建只读的函数(@property的介绍与使用)
- 【转】WCF OpenTimeout, CloseTimeout, SendTimeout, ReceiveTimeout
- 自定义的命民空间在其他程序集里无法调用
- 求字符串全排列的递归算法
- DataDir and DirectoryFactory in SolrConfig
- 导入hbase_HBase基础学习之bulkload了解
- centos 6.9 +nginx 配置GIT HTTPS服务器(证书采用自签名)
- 孩子看动画片有啥好处?
- [转载] opengl能做什么_python能做什么
- iPhone通讯录整理及vcf-CSV互转
- QT常用控件——QLabel标签控件
- c语言小游戏 贪吃蛇
- 因果推断-Uplift Model:Causal Tree
- @csrf_exempt 类的视图跨域
- 2020电信宽带费用_电信宽带套餐价格表2020
- 杂牌机搞机之旅(一)——获得root权限(刷入magisk)
- 相位相关法计算图像位移
- webpack command not found 的意外的坑 - 原因是从node开始
- 2.3.2 HMC硬件管理终端
- 暑期小学生计算机培训班,青岛小学生学习编程暑假
热门文章
- 医疗大数据:商业保险、移动医疗的崛起,正在形成闭环(二)
- qsort(bsearch,lsearch)—标准库排序,查找
- 深入理解Magento-第十章-数据操作数据收集器
- 北京点击科技有限公司董事长兼总裁——王志东经典语录2
- ASP.NET Core Web API使用静态swagger.json文件
- C# using static 声明
- SqlBulkCopy只支持SQL Server? EF Core实现支持多数据库类型的Bulk Copy
- 关于C#异步编程的建议
- 我为什么对TypeScript由黑转粉?
- ASP.NET Core学习资源汇总