コード例 #1
0
        public void ConfigureServices(IServiceCollection services)
        {
            JsonWebKey sigJsonWebKey;

            using (var rsa = RSA.Create())
            {
                var json = File.ReadAllText(Path.Combine(_env.ContentRootPath, "openid_key.txt"));
                var dic  = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
                rsa.Import(dic);
                sigJsonWebKey = new JsonWebKeyBuilder().NewSign("1", new[]
                {
                    KeyOperations.Sign,
                    KeyOperations.Verify
                }).SetAlg(rsa, "RS256").Build();
            }

            services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                          .AllowAnyMethod()
                                                          .AllowAnyHeader()));
            services.AddMvc(o => o.EnableEndpointRouting = false)
            .AddNewtonsoftJson();
            services.AddAuthorization(opts => opts.AddDefaultOAUTHAuthorizationPolicy());
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
            services.AddSIDOpenID()
            .AddAcrs(DefaultConfiguration.AcrLst)
            .AddClients(DefaultConfiguration.Clients, DefaultConfiguration.Scopes)
            .AddUsers(DefaultConfiguration.Users)
            .AddJsonWebKeys(new List <JsonWebKey> {
                sigJsonWebKey
            })
            .AddLoginPasswordAuthentication();
        }
コード例 #2
0
        private static List <JsonWebKey> GenerateJsonWebKeys()
        {
            JsonWebKey sigJsonWebKey;
            JsonWebKey encJsonWebKey;

            using (var rsa = RSA.Create())
            {
                sigJsonWebKey = new JsonWebKeyBuilder().NewSign("3", new[]
                {
                    KeyOperations.Sign,
                    KeyOperations.Verify
                }).SetAlg(rsa, "PS256").Build();
            }

            using (var rsa = RSA.Create())
            {
                encJsonWebKey = new JsonWebKeyBuilder().NewEnc("4", new[]
                {
                    KeyOperations.Encrypt,
                    KeyOperations.Decrypt
                }).SetAlg(rsa, RSAOAEPCEKHandler.ALG_NAME).Build();
            }

            return(new List <JsonWebKey>
            {
                sigJsonWebKey,
                encJsonWebKey
            });
        }
コード例 #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            JsonWebKey sigJsonWebKey;

            using (var rsa = RSA.Create())
            {
                var json = File.ReadAllText(Path.Combine(_env.ContentRootPath, "oauth_key.txt"));
                var dic  = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
                rsa.Import(dic);
                sigJsonWebKey = new JsonWebKeyBuilder().NewSign("1", new[]
                {
                    KeyOperations.Sign,
                    KeyOperations.Verify
                }).SetAlg(rsa, "RS256").Build();
            }

            services.AddMvc();
            services.AddAuthorization(opts => opts.AddDefaultOAUTHAuthorizationPolicy());
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
            services.AddSIDOAuth()
            .AddScopes(DefaultConfiguration.Scopes)
            .AddClients(DefaultConfiguration.Clients)
            .AddJsonWebKeys(new List <JsonWebKey> {
                sigJsonWebKey
            });
        }
コード例 #4
0
ファイル: Startup.cs プロジェクト: zarzayou/SimpleIdServer
        public void ConfigureServices(IServiceCollection services)
        {
            JsonWebKey oauthJsonWebKey, openidJsonWebKey = ExtractJsonWebKey();;

            using (var rsa = RSA.Create())
            {
                var json = File.ReadAllText(Path.Combine(_env.ContentRootPath, "oauth_key.txt"));
                var dic  = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
                rsa.Import(dic);
                oauthJsonWebKey = new JsonWebKeyBuilder().NewSign("1", new[]
                {
                    KeyOperations.Sign,
                    KeyOperations.Verify
                }).SetAlg(rsa, "RS256").Build();
            }

            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en"),
                    new CultureInfo("fr")
                };
                options.DefaultRequestCulture = new RequestCulture("en");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;
            });
            services.AddLogging();
            services.AddMvc(o => o.EnableEndpointRouting = false)
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, opts => { opts.ResourcesPath = "Resources"; })
            .AddDataAnnotationsLocalization()
            .AddNewtonsoftJson();
            services.AddAuthentication(opts =>
            {
                opts.DefaultAuthenticateScheme = UMAConstants.SignInScheme;
                opts.DefaultSignInScheme       = UMAConstants.SignInScheme;
                opts.DefaultChallengeScheme    = UMAConstants.ChallengeAuthenticationScheme;
            }).AddCookie(UMAConstants.SignInScheme).AddOpenIdConnect(UMAConstants.ChallengeAuthenticationScheme, options =>
            {
                options.ClientId     = "umaClient";
                options.ClientSecret = "umaClientSecret";
                options.Authority    = "https://localhost:60000";
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                options.SaveTokens   = true;
            });
            services.AddAuthorization(p => p.AddDefaultOAUTHAuthorizationPolicy());
            services.AddSIDUma(options =>
            {
                options.OpenIdJsonWebKeySignature = openidJsonWebKey;
            })
            .AddClients(DefaultConfiguration.DefaultClients)
            .AddScopes(DefaultConfiguration.DefaultScopes)
            .AddJsonWebKeys(new List <JsonWebKey> {
                oauthJsonWebKey
            });
        }
コード例 #5
0
        public void ConfigureServices(IServiceCollection services)
        {
            SimpleIdServer.Jwt.JsonWebKey sigJsonWebKey;
            var json          = File.ReadAllText("oauth_key.txt");
            var dic           = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
            var rsaParameters = new RSAParameters
            {
                Modulus  = dic.TryGet(RSAFields.Modulus),
                Exponent = dic.TryGet(RSAFields.Exponent)
            };
            var oauthRsaSecurityKey = new RsaSecurityKey(rsaParameters);

            using (var rsa = RSA.Create())
            {
                rsa.Import(dic);
                sigJsonWebKey = new JsonWebKeyBuilder().NewSign("1", new[]
                {
                    KeyOperations.Sign,
                    KeyOperations.Verify
                }).SetAlg(rsa, "RS256").Build();
            }

            services.AddMvc(o =>
            {
                o.EnableEndpointRouting = false;
            }).AddNewtonsoftJson(o => { });
            services.AddAuthorization(opts => opts.AddDefaultOAUTHAuthorizationPolicy());
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie()
            .AddJwtBearer(Constants.AuthenticationScheme, cfg =>
            {
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudiences = new List <string>
                    {
                        "gatewayClient"
                    },
                    ValidateIssuer           = false,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = oauthRsaSecurityKey
                };
            });
            services.AddSIDOAuth(o =>
            {
                o.ClientSecretExpirationInSeconds = 2;
            })
            .AddClients(DefaultConfiguration.Clients)
            .AddScopes(DefaultConfiguration.Scopes)
            .AddJsonWebKeys(new List <SimpleIdServer.Jwt.JsonWebKey> {
                sigJsonWebKey
            });
        }
コード例 #6
0
        private static IServiceCollection AddOAuthStore(this IServiceCollection services)
        {
            var        jwsGenerator = new JwsGeneratorFactory().BuildJwsGenerator();
            JsonWebKey sigJsonWebKey;
            JsonWebKey encJsonWebKey;

            using (var rsa = RSA.Create())
            {
                sigJsonWebKey = new JsonWebKeyBuilder().NewSign("1", new[]
                {
                    KeyOperations.Sign,
                    KeyOperations.Verify
                }).SetAlg(rsa, "RS256").Build();
            }

            using (var rsa = RSA.Create())
            {
                encJsonWebKey = new JsonWebKeyBuilder().NewEnc("2", new[]
                {
                    KeyOperations.Encrypt,
                    KeyOperations.Decrypt
                }).SetAlg(rsa, RSAOAEPCEKHandler.ALG_NAME).Build();
            }

            var jsonWebKeys = new List <JsonWebKey>
            {
                sigJsonWebKey,
                encJsonWebKey
            };
            var clients = new List <OAuthClient>();
            var users   = new List <OAuthUser>();
            var scopes  = new List <OAuthScope>();
            var tokens  = new ConcurrentBag <Token>();

            services.TryAddSingleton <IJsonWebKeyQueryRepository>(new DefaultJsonWebKeyQueryRepository(jsonWebKeys));
            services.TryAddSingleton <IJsonWebKeyCommandRepository>(new DefaultJsonWebKeyCommandRepository(jsonWebKeys));
            services.TryAddSingleton <IOAuthClientQueryRepository>(new DefaultOAuthClientQueryRepository(clients));
            services.TryAddSingleton <IOAuthClientCommandRepository>(new DefaultOAuthClientCommandRepository(clients));
            services.TryAddSingleton <IOAuthUserQueryRepository>(new DefaultOAuthUserQueryRepository(users));
            services.TryAddSingleton <IOAuthUserCommandRepository>(new DefaultOAuthUserCommandRepository(users));
            services.TryAddSingleton <IOAuthScopeQueryRepository>(new DefaultOAuthScopeQueryRepository(scopes));
            services.TryAddSingleton <IOAuthScopeCommandRepository>(new DefaultOAuthScopeCommandRepository(scopes));
            services.TryAddSingleton <ITokenCommandRepository>(new DefaultTokenCommandRepository(tokens));
            services.TryAddSingleton <ITokenQueryRepository>(new DefaultTokenQueryRepository(tokens));
            return(services);
        }
コード例 #7
0
ファイル: FakeJwks.cs プロジェクト: zarzayou/SimpleIdServer
        private void Init()
        {
            var builder = new JsonWebKeyBuilder();

            using (var rsa = RSA.Create())
            {
                var sig = builder.NewSign("1", new[]
                {
                    KeyOperations.Sign,
                    KeyOperations.Verify
                }).SetAlg(rsa, RSA256SignHandler.ALG_NAME).Build();
                _jsonWebKeys = new[]
                {
                    sig
                };
            }
        }
コード例 #8
0
ファイル: Startup.cs プロジェクト: zarzayou/SimpleIdServer
        private JsonWebKey ExtractJsonWebKey()
        {
            var json          = File.ReadAllText(Path.Combine(_env.ContentRootPath, "openid_puk.txt"));
            var dic           = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
            var rsaParameters = new RSAParameters
            {
                Modulus  = dic.TryGet(RSAFields.Modulus),
                Exponent = dic.TryGet(RSAFields.Exponent)
            };
            JsonWebKey sigJsonWebKey;

            using (var rsa = RSA.Create(rsaParameters))
            {
                sigJsonWebKey = new JsonWebKeyBuilder().NewSign("1", new[]
                {
                    KeyOperations.Verify
                }).SetAlg(rsa, "RS256").Build();
            }

            return(sigJsonWebKey);
        }
コード例 #9
0
ファイル: Startup.cs プロジェクト: moayyaed/CaseManagement
        public void ConfigureServices(IServiceCollection services)
        {
            JsonWebKey sigJsonWebKey;

            using (var rsa = RSA.Create())
            {
                var json = File.ReadAllText("openid_key.txt");
                var dic  = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
                rsa.Import(dic);
                sigJsonWebKey = new JsonWebKeyBuilder().NewSign("1", new[]
                {
                    KeyOperations.Sign,
                    KeyOperations.Verify
                }).SetAlg(rsa, "RS256").Build();
            }

            services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                          .AllowAnyMethod()
                                                          .AllowAnyHeader()));
            services.AddMvc();
            services.AddAuthorization(opts => opts.AddDefaultOAUTHAuthorizationPolicy());
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
            services.AddSIDOpenID(opt =>
            {
            })
            .AddClients(DefaultConfiguration.Clients)
            .AddAcrs(DefaultConfiguration.AcrLst)
            .AddUsers(DefaultConfiguration.Users)
            .AddScopes(DefaultConfiguration.Scopes)
            .AddJsonWebKeys(new List <JsonWebKey> {
                sigJsonWebKey
            })
            .AddLoginPasswordAuthentication();
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });
        }
コード例 #10
0
        private void InitializeDatabase(IApplicationBuilder app)
        {
            using (var scope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                using (var context = scope.ServiceProvider.GetService <OAuthDBContext>())
                {
                    context.Database.Migrate();
                    if (context.OAuthClients.Any())
                    {
                        return;
                    }

                    var json          = File.ReadAllText("oauth_key.txt");
                    var dic           = JsonConvert.DeserializeObject <Dictionary <string, string> >(json);
                    var rsaParameters = new RSAParameters
                    {
                        Modulus  = dic.TryGet(RSAFields.Modulus),
                        Exponent = dic.TryGet(RSAFields.Exponent)
                    };

                    SimpleIdServer.Jwt.JsonWebKey sigJsonWebKey;
                    using (var rsa = RSA.Create())
                    {
                        rsa.Import(dic);
                        sigJsonWebKey = new JsonWebKeyBuilder().NewSign("1", new[]
                        {
                            KeyOperations.Sign,
                            KeyOperations.Verify
                        }).SetAlg(rsa, "RS256").Build();
                    }

                    context.OAuthClients.AddRange(DefaultConfiguration.Clients);
                    context.OAuthScopes.AddRange(DefaultConfiguration.Scopes);
                    context.JsonWebKeys.Add(sigJsonWebKey);
                    context.SaveChanges();
                }
            }
        }
コード例 #11
0
        public void When_Build_Jwe_Then_Can_Decrypt_Into_Jws()
        {
            const string payload = "xml";

            // ARRANGE
            InitializeFakeObjects();
            JsonWebKey rsaJsonWebKey;

            using (var rsa = RSA.Create())
            {
                rsaJsonWebKey = new JsonWebKeyBuilder().NewEnc("keyId", new[]
                {
                    KeyOperations.Encrypt
                }).SetAlg(rsa, RSAOAEPCEKHandler.ALG_NAME).Build();
            }

            // ACT
            var encrypted = _jweGenerator.Build(payload, RSAOAEPCEKHandler.ALG_NAME, A192CBCHS384EncHandler.ENC_NAME, rsaJsonWebKey);
            var decrypted = _jweGenerator.Decrypt(encrypted, rsaJsonWebKey);

            // ASSERT
            Assert.Equal(payload, decrypted);
        }
コード例 #12
0
        public void When_Generate_Jws_And_Check_Signature_Then_True_Is_Returned()
        {
            // ARRANGE
            InitializeFakeObjects();
            JsonWebKey rsaJsonWebKey, ecJsonWebKey, hmac256JsonWebKey;

            using (var rsa = RSA.Create())
            {
                rsaJsonWebKey = new JsonWebKeyBuilder().NewSign("keyId", new[]
                {
                    KeyOperations.Sign
                }).SetAlg(rsa, "RS256").Build();
            }

            using (var ec = new ECDsaCng())
            {
                ecJsonWebKey = new JsonWebKeyBuilder().NewSign("keyId", new[]
                {
                    KeyOperations.Sign
                }).SetAlg(ec, "ES256").Build();
            }

            using (var hmac = new HMACSHA256())
            {
                hmac256JsonWebKey = new JsonWebKeyBuilder().NewSign("keyId", new[]
                {
                    KeyOperations.Sign
                }).SetAlg(hmac, "HS256").Build();
            }

            var payload = new JObject();

            payload.Add("sub", "thabart");

            // ACT
            var rsa256JWS        = _jwsGenerator.Build(payload.ToString(), "RS256", rsaJsonWebKey);
            var rsa384JWS        = _jwsGenerator.Build(payload.ToString(), "RS384", rsaJsonWebKey);
            var rsa512JWS        = _jwsGenerator.Build(payload.ToString(), "RS512", rsaJsonWebKey);
            var ec256JWS         = _jwsGenerator.Build(payload.ToString(), "ES256", ecJsonWebKey);
            var ec384JWS         = _jwsGenerator.Build(payload.ToString(), "ES384", ecJsonWebKey);
            var ec512JWS         = _jwsGenerator.Build(payload.ToString(), "ES512", ecJsonWebKey);
            var hs256JWS         = _jwsGenerator.Build(payload.ToString(), "HS256", hmac256JsonWebKey);
            var hs384JWS         = _jwsGenerator.Build(payload.ToString(), "HS384", hmac256JsonWebKey);
            var hs512JWS         = _jwsGenerator.Build(payload.ToString(), "HS512", hmac256JsonWebKey);
            var isRSA256JWSValid = _jwsGenerator.Check(rsa256JWS, rsaJsonWebKey);
            var isRSA384JWSValid = _jwsGenerator.Check(rsa384JWS, rsaJsonWebKey);
            var isRSA512JWSValid = _jwsGenerator.Check(rsa512JWS, rsaJsonWebKey);
            var isEC256JWSValid  = _jwsGenerator.Check(ec256JWS, ecJsonWebKey);
            var isEC384JWSValid  = _jwsGenerator.Check(ec384JWS, ecJsonWebKey);
            var isEC512JWSValid  = _jwsGenerator.Check(ec512JWS, ecJsonWebKey);
            var isHS256JWSValid  = _jwsGenerator.Check(hs256JWS, hmac256JsonWebKey);
            var isHS384JWSValid  = _jwsGenerator.Check(hs384JWS, hmac256JsonWebKey);
            var isHS512JWSValid  = _jwsGenerator.Check(hs512JWS, hmac256JsonWebKey);


            // ASSERT
            Assert.True(isRSA256JWSValid);
            Assert.True(isRSA384JWSValid);
            Assert.True(isRSA512JWSValid);
            Assert.True(isEC256JWSValid);
            Assert.True(isEC384JWSValid);
            Assert.True(isEC512JWSValid);
            Assert.True(isHS256JWSValid);
            Assert.True(isHS384JWSValid);
            Assert.True(isHS512JWSValid);
        }
コード例 #13
0
        private static IEnumerable <JsonWebKey> ExtractJsonWebKeys(Table table)
        {
            var builder = new JsonWebKeyBuilder();
            var jwks    = new List <JsonWebKey>();

            foreach (var record in table.Rows)
            {
                var        type    = record["Type"];
                var        kid     = record["Kid"];
                var        algName = record["AlgName"];
                JsonWebKey jwk     = null;
                switch (type)
                {
                case "SIG":
                    if (algName.StartsWith("ES"))
                    {
                        using (var ec = new ECDsaCng())
                        {
                            jwk = builder.NewSign(kid, new[]
                            {
                                KeyOperations.Sign,
                                KeyOperations.Verify
                            }).SetAlg(ec, algName).Build();
                        }
                    }
                    else if (algName.StartsWith("HS"))
                    {
                        using (var hmac = new HMACSHA256())
                        {
                            jwk = builder.NewSign(kid, new[]
                            {
                                KeyOperations.Sign,
                                KeyOperations.Verify
                            }).SetAlg(hmac, algName).Build();
                        }
                    }
                    else
                    {
                        using (var rsa = RSA.Create())
                        {
                            jwk = builder.NewSign(kid, new[]
                            {
                                KeyOperations.Sign,
                                KeyOperations.Verify
                            }).SetAlg(rsa, algName).Build();
                        }
                    }
                    break;

                case "ENC":
                    using (var rsa = RSA.Create())
                    {
                        jwk = builder.NewEnc(kid, new[]
                        {
                            KeyOperations.Encrypt,
                            KeyOperations.Decrypt
                        }).SetAlg(rsa, algName).Build();
                    }
                    break;
                }

                jwks.Add(jwk);
            }

            return(jwks);
        }