. NET core 1.0 implementation single sign-on load multi-server _ Practical Tips

Source: Internet
Author: User
Tags http request httpcontext json

Objective

. NET core has been out for a while, the time has also been to do technical preparation, currently want to do a single sign-on (SSO) system, before this use of. NET I used to machinekey, also conveniently in the. NET core to try one, the results found not to make, also does not work, So I began to learn online.

Implementation methods

Kung Fu is not negative, people on the Internet or more, in the github.com above issues also someone in the discussion of this problem, so find code to try, the results achieved.

Directly on the code, we need to first encapsulate a Xmlrepository,key format as follows:

 <?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:0
 9:49.1388521z</activationdate> <expirationDate>2116-10-21T10:09:49.1388521Z</expirationDate> <descriptor deserializertype= " Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializ
  Er, Microsoft.AspNetCore.DataProtection, version=1.1.0.0, culture=neutral, Publickeytoken=adb9793829ddae60 "> <descriptor> <encryption algorithm= "AES_256_CBC"/> <validation algorithm= "HMACSHA256"/> <m Asterkey p4:requiresencryption= "true" xmlns:p4= "Http://schemas.asp.net/2015/03/dataProtection" > <!--Warning : The key below is in the unencrypted form. --> &LT;VALUE&GT;WYGZNH/3DOKRYJ1OAHVQS56PWPMHEI15UJ44DPLWBYUICPNVEBWQDFYAUQ/4JBKYRNOUBARKGY5O/NZ6A2NTWA==&Lt;/value> </masterKey> </descriptor> </descriptor> </key> 

Xmlrepository Code:

public class Customfilexmlrepository:ixmlrepository
  {
    private readonly string filePath = @ "C:\keys\key.xml"; C3/>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 code:

 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 it 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 is gets called by the runtime.
    Use the Configure the HTTP request pipeline. PubLIC void Configure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory) {Loggerfacto Ry.
      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 = Cookieauthenticationdefau Lts. Authenticationscheme, Loginpath = new PathString ("/account/unauthorized/"), Accessdeniedpath = new PATHSTR ING ("/account/forbidden/"), Automaticauthenticate = True, Automaticchallenge = False, Cookiehttpon ly = 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?}");
    }); }
  }

Login code:

  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 to the Timer");
      }
      else
      {
        HttpContext.Response.ContentType = "Text/plain";
        Await HttpContext.Response.WriteAsync ("Hello old Timer");
      }
    

Attention

C:\keys\key.xml This file path can be changed, and there is also the use of shared directories or databases to achieve unified management

Here you can log in and try.

The above is a small set to introduce the. NET core 1.0 to achieve a single sign-on load multiple servers, I hope to help!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.