.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 !DEBUG
                CookieDomain="h.cn",
#endif
                DataProtectionProvider = 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 这个文件路径可以更改,还有就是也可用共享目录或数据库来实现统一管理

到此可以登录试一下。

时间: 2024-08-13 23:02:56

.net core 1.0 实现负载多服务器单点登录的相关文章

邮件服务器“单点登录”功能

现状分析: 相信我们每个人都有这样的经历,比方说银行卡多的人要具体记忆每张卡的密码挺麻烦:现代人兴 趣广泛,爱好多多,运动健身俱乐部.娱乐游戏休闲.购物理财等各种场合少不了获得入门的“通行证”,要输入各种密码.类似的情况在企业也常见,如今一些企 业大搞信息化建设,物流.数据流.资金流等纳入各种系统进行管理,工作人员经常需要在不同系统之间切换,输入不同的密码,不但繁琐,而且容易出错.有没有 这样一种可能,将众多办公系统都集成到一点,只需要登录某个系统,无需频繁切换,即可实现登录其他系统?U-Mai

【原生态跨平台: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 工具 :XShell 开发工具:VS2015企业版+ASP.NET Update1 反向代理:Nginx 是否用到了Docker?没,墙太高了,镜像拉不过来,秒懂!???!?!?! 已经都讲了,小编,你懂滴~~~

Nginx反向代理、缓存、负载均衡服务器构建

代理服务可简单的分为正向代理和反向代理: 正向代理: 用于代理内部网络对Internet的连接请求(如VPN/NAT),客户端指定代理服务器,并将本来要直接发送给目标Web服务器的HTTP请求先发送到代理服务器上,然后由代理服务器去访问Web服务器, 并将Web服务器的Response回传给客户端: 反向代理: 与正向代理相反,如果局域网向Internet提供资源,并让Internet上的其他用户可以访问局域网内资源, 也可以设置一个代理服务器, 它提供的服务就是反向代理. 反向代理服务器接受来

7.创建负载均衡服务器lb01:

创建负载均衡服务器lb01: # optimization by onekey sed -i 's#SELINUX=enforcing#SELINUX=disabled#' /etc/selinux/config grep SELINUX=disabled /etc/selinux/config setenforce 0 getenforce /etc/init.d/iptables stop /etc/init.d/iptables stop chkconfig iptables off ch

8.创建负载均衡服务器lb02:

创建负载均衡服务器lb02: # optimization by onekey sed -i 's#SELINUX=enforcing#SELINUX=disabled#' /etc/selinux/config grep SELINUX=disabled /etc/selinux/config setenforce 0 getenforce /etc/init.d/iptables stop /etc/init.d/iptables stop chkconfig iptables off ch

CentOS 5.5下安装mysql5.1.57+php5.2.17(FastCGI)+nginx1.0.1高性能Web服务器 [转载]

CentOS 5.5下安装mysql5.1.57+php5.2.17(FastCGI)+nginx1.0.1高性能Web服务器 [转载] 2012年09月05日 ⁄ Linux技术 ⁄ 共 12362字 ⁄ 字号 小 中 大 ⁄ 暂无评论 ⁄ 阅读 85 views 次 由于生产环境都是freebsd平台,之前也写了一篇FreeBSD下安装 mysql5.1.56+php5.2.17(FastCGI)+nginx1.0.1高性能Web服务器,有童鞋想要帮忙写一篇关于centos下的安 装教程,其

ASP.NET Core 3.0 入门

原文:ASP.NET Core 3.0 入门 课程简介 与2.x相比发生的一些变化,项目结构.Blazor.SignalR.gRPC等 课程预计结构 ASP.NET Core 3.0项目架构简介 ASP.NET Core MVC 简介 Blazor SignalR Web API gRPC 发布 一. 创建项目 dotnet core 本质上是控制台应用 1. DI 依赖注入(Dependency Injection) IoC 容器(Inversion of Control)控制反转 注册(服务

C#手动做一个负载均衡服务器

思路 负载均衡服务器最出名的当数 Nginx了.Nginx服务器通过异步的方式把连接转发给内网和N个服务器,用来分解单台应用服务器的压力,了解了原理及场景后,用C#来实现一个.思路如下: 1. 使用一个站点的 Application_BeginRequest 来接收连接,转发连接. 2. 对各类静态资源做单独处理,(可转可不转) 3. 可以转发Get,Post,异步转发. 4. 对指定的请求,转发到同一台服务器,保持使用者的登录状态. 实现 Vs2015建一个Mvc建站: localhost:1

一起学ASP.NET Core 2.0学习笔记(二): ef core2.0 及mysql provider 、Fluent API相关配置及迁移

不得不说微软的技术迭代还是很快的,上了微软的船就得跟着她走下去,前文一起学ASP.NET Core 2.0学习笔记(一): CentOS下 .net core2 sdk nginx.supervisor.mysql环境搭建搭建好了.net core linux的相关环境,今天就来说说ef core相关的配置及迁移: 简介: Entity Framework(以下简称EF) 是微软以 ADO.NET 为基础所发展出来的对象关系对应 (O/R Mapping) 解决方案,EF Core是Entity