欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net core 1.0 实现单点登录负载多服务器

程序员文章站 2023-11-24 14:49:58
前言   .net core 出来有一时间了,这段时间也一直在做技术准备,目前想做一个单点登录(sso)系统,在这之前用.net时我用习惯了machinekey ,也顺手...

前言

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

到此可以登录试一下。

以上所述是小编给大家介绍的.net core 1.0 实现单点登录负载多服务器的全部叙述,希望对大家有所帮助!