温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-05-21 14:30:48 来源:亿速云 阅读:198 作者:小新 栏目:开发技术

这篇文章将为大家详细讲解有关.net core 1.0如何实现单点登录负载多服务器,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

实现方法

我们需要先封装一个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如何实现单点登录负载多服务器”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI