КАК ИСПОЛЬЗОВАТЬ в Linux, IdentityServer4 с сертификатом LetsEncript для аутентификации? - PullRequest
1 голос
/ 02 августа 2020

Подскажите, пожалуйста, как настроить сертификат подписи для производства?

При разработке webapp работает нормально, я использую собственный сертификат в Windows. Но для производства в Linux я не знаю, как использовать сертификат. На самом деле я использую LetsEncript для https, и как CA, я полагаю, я могу использовать их сертификат для аутентификации с IdentityServer.

Это то, что у меня есть прямо сейчас.

Запуск IdentityServer. cs файл:

namespace IdentityServer
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        public IWebHostEnvironment Environment { get; }
        public Startup(IConfiguration configuration, IWebHostEnvironment 
         environment)
        {
            Configuration = configuration;
            Environment = environment;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.Configure<ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | 
                ForwardedHeaders.XForwardedProto;
            });
 
            services.AddDbContext<IdentityDbContext>(
                options => options.UseNpgsql(Configuration.GetConnectionString("IdentityConnect")));    
            services.AddScoped<IPasswordHasher<Entities.User>, 
                PasswordHasher<Entities.User>>();
            services.AddScoped<ILocalUserService, LocalUserService>();

            var builder = services.AddIdentityServer()
                .AddInMemoryIdentityResources(Config.Ids)
                .AddInMemoryApiResources(Config.Apis)
                .AddInMemoryClients(Config.Clients);
                 
            builder.AddProfileService<LocalUserProfileService>();

            if (Environment.IsDevelopment())
            {
                builder.AddSigningCredential(LoadCertificateFromStore());
            }
             
            IdentityModelEventSource.ShowPII = true;
        }
     
        public void Configure(IApplicationBuilder app)
        {
            app.UseForwardedHeaders();

            if (Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts(); 
            }

            app.UseStaticFiles();
            app.UseRouting();
            app.UseIdentityServer();  
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }
        

        public X509Certificate2 LoadCertificateFromStore()
        {  
            string thumbPrint = "73ppppp1958888886d772222270000dbddb1aa37";
            using (var store = new X509Store(StoreName.My, 
               StoreLocation.LocalMachine))
            {
                store.Open(OpenFlags.ReadOnly);
                var certCollection = 
                    store.Certificates.Find(X509FindType.FindByThumbprint,
                    thumbPrint, true);
                if (certCollection.Count == 0)
                {
                    throw new Exception("The specified certificate wasn't found.");
                }
                return certCollection[0];
            }
        }

Appsetting. Json file: В нем нет ничего особенного, только строка подключения для identityserver.

Файл Config.cs:

namespace IdentityServer
{
    public static class Config
    { 
        public static IEnumerable<IdentityResource> Ids => new IdentityResource[]
        { 
           ...Irrelevant Code
        }
        public static IEnumerable<ApiResource> Apis => new ApiResource[] 
        {  
          ...Irrelevant Code
        }

        public static IEnumerable<Client> Clients =>
            new Client[] 
            {
                new Client
                {
                    AccessTokenType = AccessTokenType.Reference,
                    AccessTokenLifetime = 3600, 
                    AllowOfflineAccess = true,

                    UpdateAccessTokenClaimsOnRefresh = true,  
                    ClientName = "WebApp",
                    ClientId = "webapp",

                    RequireConsent = false,
                    AllowedGrantTypes = GrantTypes.Code,  
                    RequirePkce = true, 
                    RedirectUris = new List<string>()
                    {
                         // Shoud I use here a domain for production like https://www.example.com:44300/signin-oidc ?
                        "https://localhost:44300/signin-oidc"
                    },
                    PostLogoutRedirectUris = new List<string>()
                    {
                         // Shoud I use here a domain for production like https://www.example.com:44300/signout-callback-oidc ?
                        "https://localhost:44300/signout-callback-oidc"
                    },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        IdentityServerConstants.StandardScopes.Address,      
                        "subscriptionlevel"
                    },
                    ClientSecrets =
                    {
                        new Secret("fakesecret".Sha256())
                    }
                } };

1 Ответ

0 голосов
/ 03 августа 2020

Теоретически вы можете использовать один и тот же закрытый ключ как для подписи, так и для HTTPS, но я рекомендую вам хранить их отдельно для простоты. Так, например, вы можете независимо вращать клавиши (менять клавиши). И использование токенов, и HTTPS зависят от ключей private / publi c, поэтому существует много общих концепций.

...