一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - ASP.NET教程 - .net core 1.0 實現單點登錄負載多服務器

.net core 1.0 實現單點登錄負載多服務器

2020-03-11 14:53韓天偉 ASP.NET教程

這篇文章主要介紹了.net core 1.0 實現單點登錄負載多服務器的相關資料,非常不錯,具有參考借鑒價值,感興趣的朋友可以參考下

前言

  .net core 出來有一時間了,這段時間也一直在做技術準備,目前想做一個單點登錄(SSO)系統,在這之前用.net時我用習慣了machineKey ,也順手在.net core 中嘗試了一上,結果發現不好使了,也不起作用,于是開始了網上學習。

實現方法

  功夫不負有心人,網上高人還是多,在github.com上面ISSUES中也有人在討論此問題,于是找到代碼嘗試,結果實現了。

  直接上代碼,我們需要先封裝一個XmlRepository,Key的格式如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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?}");
      });
    }
  }

登錄代碼:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 實現單點登錄負載多服務器的全部敘述,希望對大家有所幫助!

原文鏈接:http://www.cnblogs.com/hantianwei/p/5699370.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: yw在线观看成人免费 | 男生的j桶女人屁免费视频 男生操男生 | 美女漫画网| 亚洲图片一区二区三区 | 久久热这里面只有精品 | 四虎现在的网址入口2022 | 白发在线视频播放观看免费 | 亚洲国产日韩欧美mv | 欧美另类杂交a | 激情视频在线播放 | 免费的强动漫人物的 | 调教麻麻成贱m | 四虎e234hcom| 国产精品成人亚洲 | 免费日本视频 | chanelpreston欧美网站 | zoomkool最新版| 四虎在线永久视频观看 | 欧美一区二区三区四区五区六区 | 亚洲品质自拍视频 | 好大好爽好涨太深了小喜 | 鬼吹灯之天星术免费观看 | 欧美一级特黄aaa大片 | 国产精品久久久久久久久久久威 | 精品视频99 | 午夜精品久视频在线观看 | 2022最新国产在线不卡a | 久久久久免费视频 | 成人欧美一区二区三区黑人 | 色综色天天综合网 | 国产成人在线播放 | 欧美一卡2卡3卡无卡 | 三上悠亚精品专区久久 | 香蕉久久ac一区二区三区 | 亚洲是图你懂的 | 亚洲高清一区二区三区四区 | 99国产高清久久久久久网站 | 狠狠色狠狠色综合系列 | 99国产国人青青视频在线观看 | 边摸边吃奶边做爽视频免费 | 美女禁区视频免费观看精选 |