.net core 1.0 实现负载多服务器单点登录
前言
.net core 出来有一时间了,这段时间也一直在做技术准备,目前想做一个单点登录(SSO)系统,在这之前用.net时我用习惯了machineKey ,也顺手在.net core 中尝试了一上,结果发现不好使了,也不起作用,于是开始了网上学习。
实现方法
功夫不负有心人,网上高人还是多,在github.com上面ISSUES中也有人在讨论此问题,于是找到代码尝试,结果实现了。
直接上代码,我们需要先封装一个XmlRepository,Key的格式如下:
<?xml version="1.0" encoding="utf-8"?> <key id="cbb8a41a-9ca4-4a79-a1de-d39c4e307d75" version="1"><creationDate>2016-07-23T10:09:49.1888876Z</creationDate><activationDate>2016-07-23T10:09:49.1388521Z</activationDate><expirationDate>2116-10-21T10:09:49.1388521Z</expirationDate><descriptor deserializerType="Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=1.1.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"><descriptor><encryption algorithm="AES_256_CBC" /><validation algorithm="HMACSHA256" /><masterKey p4:requiresEncryption="true" xmlns:p4="http://schemas.asp.net/2015/03/dataProtection"><!-- Warning: the key below is in an unencrypted form. --><value>WYgZNh/3dOKRYJ1OAhVqs56pWPMHei15Uj44DPLWbYUiCpNVEBwqDfYAUq/4jBKYrNoUbaRkGY5o/NZ6a2NTwA==</value></masterKey></descriptor></descriptor> </key>
XmlRepository代码:
public class CustomFileXmlRepository : IXmlRepository{private readonly string filePath = @"C:\keys\key.xml";public virtual IReadOnlyCollection<XElement> GetAllElements(){return GetAllElementsCore().ToList().AsReadOnly();}private IEnumerable<XElement> GetAllElementsCore(){yield return XElement.Load(filePath);}public virtual void StoreElement(XElement element, string friendlyName){if (element == null){throw new ArgumentNullException(nameof(element));}StoreElementCore(element, friendlyName);}private void StoreElementCore(XElement element, string filename){}}
Startup代码:
public class Startup{public Startup(IHostingEnvironment env){var builder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true).AddEnvironmentVariables();Configuration = builder.Build();}public IConfigurationRoot Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddSingleton<IXmlRepository, CustomFileXmlRepository>();services.AddDataProtection(configure =>{configure.ApplicationDiscriminator = "Htw.Web";});// Add framework services. services.AddMvc();}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){loggerFactory.AddConsole(Configuration.GetSection("Logging"));loggerFactory.AddDebug();if (env.IsDevelopment()){app.UseDeveloperExceptionPage();app.UseBrowserLink();}else{app.UseExceptionHandler("/Home/Error");}app.UseStaticFiles();app.UseCookieAuthentication(new CookieAuthenticationOptions(){AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme,LoginPath = new PathString("/Account/Unauthorized/"),AccessDeniedPath = new PathString("/Account/Forbidden/"),AutomaticAuthenticate = true,AutomaticChallenge = false,CookieHttpOnly = true,CookieName = "MyCookie",ExpireTimeSpan = TimeSpan.FromHours(2), #if !DEBUGCookieDomain="h.cn", #endifDataProtectionProvider = null});app.UseMvc(routes =>{routes.MapRoute(name: "default",template: "{controller=Home}/{action=Index}/{id?}");});}}
登录代码:
public async void Login(){if (!HttpContext.User.Identities.Any(identity => identity.IsAuthenticated)){var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "bob") }, CookieAuthenticationDefaults.AuthenticationScheme));await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user);HttpContext.Response.ContentType = "text/plain";await HttpContext.Response.WriteAsync("Hello First timer");}else{HttpContext.Response.ContentType = "text/plain";await HttpContext.Response.WriteAsync("Hello old timer");}}
注意
C:\keys\key.xml 这个文件路径可以更改,还有就是也可用共享目录或数据库来实现统一管理
到此可以登录试一下。
转载于:https://www.cnblogs.com/hantianwei/p/5699370.html
.net core 1.0 实现负载多服务器单点登录相关推荐
- 举个栗子!Tableau 技巧(158):如何实现双域的服务器单点登录
单点登录(SingleSignOn,SSO),是指用户只需一次登录就可以访问所有相互信任的应用系统,不需要管理员对用户的登录状态或其他信息进行修改. 实际分析应用中,很多企业都有单点登录的需求.例如: ...
- 教程篇(7.0) 06. FortiGate基础架构 单点登录(FSSO) ❀ Fortinet 网络安全专家 NSE 4
在本课中,你将学习Fortinet单点登录(FSSO).当你使用此功能时,你的用户不需要每次访问不同的网络资源时都登录. 本节课,你将学习这上图显示的主题. 通过展示理解SSO概念的能力,你将能 ...
- 临近年关,修复ASP.NET Core因浏览器内核版本引发的单点登录故障
临近年关,咨询师提出360.搜狗急速浏览器无法单点登录到公司核心产品WD: 重定向过多. 现象 经过测试, 出现单点登陆故障的是搜狗.360等双核浏览器(默认使用Chrome内核), 较新式的Edge ...
- 邮件服务器“单点登录”功能
现状分析: 相信我们每个人都有这样的经历,比方说银行卡多的人要具体记忆每张卡的密码挺麻烦:现代人兴 趣广泛,爱好多多,运动健身俱乐部.娱乐游戏休闲.购物理财等各种场合少不了获得入门的"通行证 ...
- 【原生态跨平台:ASP.NET Core 1.0(非Mono)在 Ubuntu 14.04 服务器上一对一的配置实现-篇幅2】...
在 [原生态跨平台:ASP.NET Core 1.0(非Mono)在 Ubuntu 14.04 服务器上一对一的配置实现-篇幅1] 环境:Ubuntu 14.04 服务器版 虚拟机:Vmware 10 ...
- VSCode------搭建.net core 2.0,并配置到IIS服务器
前奏 安装VSCode最新版: https://code.visualstudio.com/ 安装window server hosting,发布和部署到IIS使用: https://www.micr ...
- Docker ASP.NET Core 2.0 微服务跨平台实践
本篇博文的目的:在 Mac OS 中使用 VS Code 开发 ASP.NET Core 2.0 应用程序,然后在 Ubuntu 服务器配置 Docker 环境,并使用 Docker 运行 Consu ...
- Docker Consul Fabio ASP.NET Core 2.0 微服务跨平台实践
相关博文: Ubuntu 简单安装 Docker Mac OS.Ubuntu 安装及使用 Consul Consul 服务注册与服务发现 Fabio 安装和简单使用 阅读目录: Docker 运行 C ...
- .NET Core 3.0 正式公布:新特性详细解读
点击蓝字"dotNET匠人"关注我哟 加个"星标★",每日 7:15,好文必达! 作者丨Richard Lander 译者丨核子可乐 策划丨赵钰莹 近日,.NE ...
最新文章
- Spring-AOP的实现方法
- java生成三级级联的数据,微信小程序三级级联,自定义json数据源
- 【机器学习】岭回归(L2正则在干嘛!)
- CentOS 6.5安装VNC server
- 每次有人来家里,总有人问我这个积木在哪买的
- 自定义URL Scheme完全指南
- java java.doc_使用 javadoc 自动生成 Java 文档
- oracle:实现滑动平均效果
- pytorch torch.rand
- 【No.4 变量作用域】
- ImportError: No module named ‘BaseHTTPServer‘:解决方案
- java Web开发环境配置
- Python TCP 学习笔记
- pandas nat_EDA神器pandas-profiling万岁?
- 翻译: swift5 iOS中的自动布局教程:Auto Layout入门
- Azure云centos7安装图形化界面
- 2010年度 中国WEB应用防火墙厂家和产品大全
- 我的世界java边境之地_我的世界边境之地是否存在 我的世界边境之地大揭秘
- gitlab项目的备份与迁移
- c语言define作用范围,#define的作用(C语言)
热门文章
- linux访问网页元素,Linux_DOM和JAVASCRIPT访问页面上的元素,访问方法:getElementById() - phpStudy...
- C语言求m中n个数字的组合
- 分峰截幅c语言算法,面向桥梁健康监测的复合传感技术研究
- 欧洲最大云服务公司火灾!数百万网站出现故障企业网络推广大型瘫痪现场!...
- python调用libs.dbutil_Python 使用 PyMysql、DBUtils 创建连接池,提升性能
- html中的li排成一行怎么写,html怎么实现li元素有点并分列
- 博途v15安装过程中提示出错_博途V15.1对应的V90 HSP和GSD文件安装
- 前置机上如何地址转换_canvas原生层级较高,遮盖自定义tabbar,转换为图片解决...
- http://www.secrepo.com 安全相关的数据获取源
- Linux的nm查看动态和静态库中的符号