因为公司提高认证中心(底层就是IdentityServer4)的高可用性,所以核心的服务都是要求至少2个pod,
当把服务直接伸缩为2个pod的时候发现,每次在登录的时候有一次是没有反应的,上网看了一下issues:
https://hub.fastgit.org/IdentityServer/IdentityServer4/issues/2205
IdentityServer4服务本身是无状态的,所以我伸缩2个pod后对外提供jwt token的接口都是好用的,但就是登录有问题,也就是上面issues里面说的 encryption keys的问题
这个东东其实就是微软里面的data protection,上网抓了一篇文章(具体文章忘了,很好找)
1)增加DataProtectionExtensions
public static void ConfigureDataProtection(this IServiceCollection services) { services.AddDataProtection() .SetApplicationName("your app name") .AddKeyManagementOptions(options => { //配置自定义XmlRepository options.XmlRepository = new XmlRepository(); }); }
然后实现 XmlRepository:
public class XmlRepository : IXmlRepository { private readonly string _KeyContentPath = ""; public XmlRepository() { _KeyContentPath = Path.Combine(Directory.GetCurrentDirectory(), "your file floder", "your key name.xml"); } public IReadOnlyCollection<XElement> GetAllElements() { //加载key信息 var elements = new List<XElement>() { XElement.Load(_KeyContentPath) }; return elements; } public void StoreElement(XElement element, string friendlyName) { //本文忽略实现存储功能,因为我们只需要读取已存在的Key即可 } }
生成的keys的格式参考这篇文章:
https://www.cnblogs.com/savorboard/p/dotnetcore-data-protected-farm.html
如果使用代码,可以写一个单元测试
using System; using System.IO; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection.SystemWeb; using Microsoft.Extensions.DependencyInjection; namespace DataProtectionDemo { public class MyDataProtectionStartup : DataProtectionStartup { public override void ConfigureServices(IServiceCollection services) { services.AddDataProtection() .SetApplicationName("my-app") .PersistKeysToFileSystem(new DirectoryInfo(@"\serversharemyapp-keys")); } } }
将文件放进代码,然后打镜像,部署即可