コード例 #1
0
 private static void ConfigureServices(IServiceCollection services)
 {
     services
     .AddHttpMessageSigning()
     .UseKeyId("e0e8dcd638334c409e1b88daf821d135")
     .UseSignatureAlgorithm(SignatureAlgorithm.CreateForSigning("yumACY64r%hm"))
     .UseDigestAlgorithm(HashAlgorithmName.SHA256)
     .UseExpires(TimeSpan.FromMinutes(1))
     .UseHeaders(
         (HeaderName)"Dalion-App-Id",
         HeaderName.PredefinedHeaderNames.Date,
         HeaderName.PredefinedHeaderNames.Created,
         HeaderName.PredefinedHeaderNames.Expires)
     .Services
     .AddHttpMessageSignatureVerification()
     .UseAspNetCoreSignatureVerification()
     .UseClient(Client.Create(
                    "e0e8dcd638334c409e1b88daf821d135",
                    "HttpMessageSigningSampleHMAC",
                    SignatureAlgorithm.CreateForVerification("yumACY64r%hm"),
                    options => options.Claims = new [] {
         new Claim(SignedHttpRequestClaimTypes.Role, "users.read")
     }
                    ));
 }
コード例 #2
0
 public void GivenNullOrEmptyEncryptionKey_DoesNotThrow(string nullOrEmpty)
 {
     using (var hmac = SignatureAlgorithm.CreateForVerification(_unencryptedKey, HashAlgorithmName.SHA384)) {
         Action act = () => _sut.FromSignatureAlgorithm(hmac, nullOrEmpty);
         act.Should().NotThrow();
     }
 }
        private void ConfigureServices(IServiceCollection services)
        {
            var keyId = new KeyId("e0e8dcd638334c409e1b88daf821d135");

            services
            .AddHttpMessageSigning(
                keyId,
                provider => new SigningSettings {
                SignatureAlgorithm  = SignatureAlgorithm.CreateForSigning("yumACY64r%hm"),
                DigestHashAlgorithm = HashAlgorithmName.SHA256,
                Expires             = TimeSpan.FromMinutes(1),
                Headers             = new[] {
                    (HeaderName)"Dalion-App-Id"
                },
                Events = new RequestSigningEvents {
                    OnRequestSigned = OnRequestSigned
                }
            })
            .AddHttpMessageSignatureVerification(provider => {
                var clientStore = new InMemoryClientStore();
                clientStore.Register(new Client(
                                         keyId,
                                         "HttpMessageSigningSampleHMAC",
                                         SignatureAlgorithm.CreateForVerification("yumACY64r%hm"),
                                         TimeSpan.FromMinutes(5),
                                         new Claim(SignedHttpRequestClaimTypes.Role, "users.read")));
                return(clientStore);
            })
            .AddHttpClient <SenderService>(config => config.BaseAddress = new Uri("https://httpbin.org"))
            .AddHttpMessageHandler(provider => new HttpRequestSigningHandler(provider.GetRequiredService <IRequestSignerFactory>().CreateFor(keyId)))
            .AddHttpMessageHandler(() => new FakeDelegatingHandler(new HttpResponseMessage(HttpStatusCode.Created)))
            .Services
            .AddTransient <HttpRequestSigningHandler>();
        }
コード例 #4
0
 private void ConfigureServices(IServiceCollection services)
 {
     services
     .AddHttpMessageSigning()
     .UseKeyId("e0e8dcd638334c409e1b88daf821d135")
     .UseSignatureAlgorithm(SignatureAlgorithm.CreateForSigning("yumACY64r%hm"))
     .UseDigestAlgorithm(HashAlgorithmName.SHA256)
     .UseExpires(TimeSpan.FromMinutes(1))
     .UseHeaders((HeaderName)"Dalion-App-Id")
     .UseOnRequestSigningEvent((message, settings) => {
         UpdateNonceEnabled(settings);
         return(Task.CompletedTask);
     })
     .Services
     .AddHttpMessageSignatureVerification()
     .UseAspNetCoreSignatureVerification()
     .UseClient(Client.Create(
                    "e0e8dcd638334c409e1b88daf821d135",
                    "HttpMessageSigningSampleHMAC",
                    SignatureAlgorithm.CreateForVerification("yumACY64r%hm"),
                    options => options.Claims = new [] {
         new Claim(SignedHttpRequestClaimTypes.Role, "users.read")
     }
                    ));
 }
コード例 #5
0
        public ISignatureAlgorithm ToSignatureAlgorithm()
        {
            switch (Type)
            {
            case string str when str.Equals("rsa", StringComparison.OrdinalIgnoreCase):
                using (var rsaForVerification = new RSACryptoServiceProvider())
                {
                    rsaForVerification.FromXml(Parameter);
                    var paramsForVerification = rsaForVerification.ExportParameters(false);

                    return(SignatureAlgorithm.CreateForVerification(paramsForVerification, new HashAlgorithmName(HashAlgorithm)));
                }

            case string str when str.Equals("ecdsa", StringComparison.OrdinalIgnoreCase):
                using (var ecdsaForVerification = ECDsa.Create())
                {
                    ecdsaForVerification.FromXml(Parameter);
                    var paramsForVerification = ecdsaForVerification.ExportParameters(false);

                    return(SignatureAlgorithm.CreateForVerification(paramsForVerification, new HashAlgorithmName(HashAlgorithm)));
                }

            case string str when str.Equals("hmac", StringComparison.OrdinalIgnoreCase):
                return(SignatureAlgorithm.CreateForVerification(Parameter, new HashAlgorithmName(HashAlgorithm)));

            default:
                throw new NotSupportedException($"The specified signature algorithm type ({Type ?? "[null]"}) cannot be deserialized.");
            }
        }
コード例 #6
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // Register sample client
            var clientStore = app.ApplicationServices.GetRequiredService <IClientStore>();

            clientStore
            .Register(new Client(
                          new KeyId("e0e8dcd638334c409e1b88daf821d135"),
                          "HttpMessageSigningSampleHMAC",
                          SignatureAlgorithm.CreateForVerification("G#6l$!D16E2UPoYKu&oL@AjAOj9vipKJTSII%*8iY*q6*MOis2R", HashAlgorithmName.SHA512),
                          TimeSpan.FromMinutes(5),
                          new Claim(SignedHttpRequestClaimTypes.Role, "user.read")))
            .GetAwaiter().GetResult();

            app
            .UseRouting()
            .UseAuthentication()
            .UseAuthorization()
            .UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }
コード例 #7
0
        private void ConfigureServices(IServiceCollection services)
        {
            var keyId = new KeyId("e0e8dcd638334c409e1b88daf821d135");

            services
            .AddHttpMessageSigning()
            .UseKeyId(keyId)
            .UseSignatureAlgorithm(SignatureAlgorithm.CreateForSigning("yumACY64r%hm"))
            .UseDigestAlgorithm(HashAlgorithmName.SHA256)
            .UseExpires(TimeSpan.FromMinutes(1))
            .UseHeaders((HeaderName)"Dalion-App-Id")
            .UseOnSigningStringComposedEvent(OnSigningStringComposed)
            .UseOnRequestSignedEvent(OnRequestSigned)
            .Services
            .AddHttpMessageSignatureVerification()
            .UseAspNetCoreSignatureVerification()
            .UseClient(Client.Create(
                           keyId,
                           "HttpMessageSigningSampleHMAC",
                           SignatureAlgorithm.CreateForVerification("yumACY64r%hm"),
                           options => options.Claims = new [] {
                new Claim(SignedHttpRequestClaimTypes.Role, "users.read")
            }
                           ))
            .Services
            .AddHttpClient <SenderService>(config => config.BaseAddress = new Uri("https://httpbin.org"))
            .AddHttpMessageHandler(provider => new HttpRequestSigningHandler(provider.GetRequiredService <IRequestSignerFactory>().CreateFor(keyId)))
            .AddHttpMessageHandler(() => new FakeDelegatingHandler(new HttpResponseMessage(HttpStatusCode.Created)))
            .Services
            .AddTransient <HttpRequestSigningHandler>();
        }
            public async Task WhenSignatureVerificationSucceeds_InvokesConfiguredCallback()
            {
                _request.Headers["Authorization"] = "TestScheme abc123";

                var principal     = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("name", "john.doe") }));
                var successResult = new RequestSignatureVerificationResultSuccess(
                    new Client("c1", "test", SignatureAlgorithm.CreateForVerification("s3cr3t"), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)),
                    new Signature(),
                    principal);

                A.CallTo(() => _options.RequestSignatureVerifier.VerifySignature(
                             A <IOwinRequest> .That.Matches(ConvertedRequest),
                             A <SignedHttpRequestAuthenticationOptions> ._))
                .Returns(successResult);

                RequestSignatureVerificationResult resultFromCallback = null;

                _options.OnIdentityVerified = (request, success) => {
                    resultFromCallback = success;
                    return(Task.CompletedTask);
                };

                await _method();

                resultFromCallback.Should().Be(successResult);
            }
コード例 #9
0
        public async Task RegistersClientsInStore()
        {
            using (var provider = new ServiceCollection()
                                  .AddHttpMessageSignatureVerification()
                                  .UseSqlServerClientStore(new SqlServerClientStoreSettings {
                ClientsTableName = "clients",
                ConnectionString = _connectionString,
                ClientCacheEntryExpiration = TimeSpan.FromMinutes(1)
            })
                                  .UseSqlServerNonceStore(new SqlServerNonceStoreSettings {
                NonceTableName = "nonces",
                ConnectionString = _connectionString
            })
                                  .UseClient(Client.Create(
                                                 "e0e8dcd638334c409e1b88daf821d135",
                                                 "HttpMessageSigningSampleHMAC",
                                                 SignatureAlgorithm.CreateForVerification("yumACY64r%hm"),
                                                 options => options.Claims = new [] {
                new Claim(SignedHttpRequestClaimTypes.Role, "users.read")
            }
                                                 ))
                                  .Services
                                  .BuildServiceProvider()) {
                var clientStore = provider.GetRequiredService <IClientStore>();
                clientStore.GetType().Name.Should().Be("CachingClientStore");
                var registeredClient = await clientStore.Get("e0e8dcd638334c409e1b88daf821d135");

                registeredClient.Should().NotBeNull();
                registeredClient.Name.Should().Be("HttpMessageSigningSampleHMAC");
            }
        }
コード例 #10
0
 public static void ConfigureServices(IServiceCollection services)
 {
     services
     .AddLogging(configure => configure.AddConsole().SetMinimumLevel(LogLevel.Debug))
     .AddHttpMessageSigning(
         new KeyId("e0e8dcd638334c409e1b88daf821d135"),
         provider => new SigningSettings {
         SignatureAlgorithm  = SignatureAlgorithm.CreateForSigning("yumACY64r%hm"),
         DigestHashAlgorithm = HashAlgorithmName.SHA256,
         Expires             = TimeSpan.FromMinutes(1),
         Headers             = new [] {
             (HeaderName)"Dalion-App-Id"
         }
     })
     .AddHttpMessageSignatureVerification(provider => {
         var clientStore = new InMemoryClientStore();
         clientStore.Register(new Client(
                                  new KeyId("e0e8dcd638334c409e1b88daf821d135"),
                                  "HttpMessageSigningSampleHMAC",
                                  SignatureAlgorithm.CreateForVerification("yumACY64r%hm"),
                                  TimeSpan.FromMinutes(5),
                                  new Claim(SignedHttpRequestClaimTypes.Role, "users.read")));
         return(clientStore);
     });
 }
            public async Task WhenSignatureVerificationFails_InvokesConfiguredCallback()
            {
                _request.Headers["Authorization"] = "TestScheme abc123";

                var failureResult = new RequestSignatureVerificationResultFailure(
                    new Client("c1", "test", SignatureAlgorithm.CreateForVerification("s3cr3t"), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)),
                    new Signature(),
                    SignatureVerificationFailure.HeaderMissing("A header is missing.", null));

                A.CallTo(() => _options.RequestSignatureVerifier.VerifySignature(
                             A <IOwinRequest> .That.Matches(ConvertedRequest),
                             A <SignedHttpRequestAuthenticationOptions> ._))
                .Returns(failureResult);

                RequestSignatureVerificationResult resultFromCallback = null;

                _options.OnIdentityVerificationFailed = (request, failure) => {
                    resultFromCallback = failure;
                    return(Task.CompletedTask);
                };

                await _method();

                resultFromCallback.Should().Be(failureResult);
            }
コード例 #12
0
 public void GivenNullDataRecord_ThrowsArgumentNullException()
 {
     using (var hmac = SignatureAlgorithm.CreateForVerification(_unencryptedKey, HashAlgorithmName.SHA384)) {
         Action act = () => _sut.SetSignatureAlgorithm(null, hmac, _encryptionKey);
         act.Should().Throw <ArgumentNullException>();
     }
 }
            public async Task WhenSignatureVerificationSucceeds_ReturnsAuthenticationTicket()
            {
                _request.Headers["Authorization"] = "TestScheme abc123";

                var principal     = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim("name", "john.doe") }));
                var successResult = new RequestSignatureVerificationResultSuccess(
                    new Client(
                        "c1",
                        "test",
                        SignatureAlgorithm.CreateForVerification("s3cr3t"),
                        TimeSpan.FromMinutes(1),
                        TimeSpan.FromMinutes(1),
                        RequestTargetEscaping.RFC3986),
                    new HttpRequestForVerification(),
                    principal);

                A.CallTo(() => _options.RequestSignatureVerifier.VerifySignature(
                             A <IOwinRequest> .That.Matches(ConvertedRequest),
                             A <SignedHttpRequestAuthenticationOptions> ._))
                .Returns(successResult);

                var actual = await _method();

                actual.Should().BeEquivalentTo(new AuthenticationTicket(principal.Identity as ClaimsIdentity, new AuthenticationProperties()));
            }
コード例 #14
0
 private void ConfigureServices(IServiceCollection services)
 {
     services
     .AddHttpMessageSigning(
         new KeyId("e0e8dcd638334c409e1b88daf821d135"),
         provider => new SigningSettings {
         SignatureAlgorithm  = SignatureAlgorithm.CreateForSigning("yumACY64r%hm"),
         DigestHashAlgorithm = HashAlgorithmName.SHA256,
         Expires             = TimeSpan.FromMinutes(1),
         Headers             = new[] {
             (HeaderName)"Dalion-App-Id"
         },
         Events = new RequestSigningEvents {
             OnRequestSigning = (message, settings) => {
                 UpdateNonceEnabled(settings);
                 return(Task.CompletedTask);
             }
         }
     })
     .AddHttpMessageSignatureVerification(provider => {
         var clientStore = new InMemoryClientStore();
         clientStore.Register(new Client(
                                  new KeyId("e0e8dcd638334c409e1b88daf821d135"),
                                  "HttpMessageSigningSampleHMAC",
                                  SignatureAlgorithm.CreateForVerification("yumACY64r%hm"),
                                  TimeSpan.FromMinutes(5),
                                  new Claim(SignedHttpRequestClaimTypes.Role, "users.read")));
         return(clientStore);
     });
 }
コード例 #15
0
 public void GivenNullOrEmptyEncryptionKey_DoesNotEncryptParameter(string nullOrEmpty)
 {
     using (var hmac = SignatureAlgorithm.CreateForVerification(_unencryptedKey, HashAlgorithmName.SHA384)) {
         _sut.SetSignatureAlgorithm(_dataRecord, hmac, nullOrEmpty);
         _dataRecord.SigParameter.Should().Be(_unencryptedKey);
         _dataRecord.IsSigParameterEncrypted.Should().BeFalse();
     }
 }
コード例 #16
0
 public void GivenNullOrEmptyEncryptionKey_DoesNotEncryptParameter(string nullOrEmpty)
 {
     using (var hmac = SignatureAlgorithm.CreateForVerification(_unencryptedKey, HashAlgorithmName.SHA384)) {
         var actual = _sut.FromSignatureAlgorithm(hmac, nullOrEmpty);
         actual.Parameter.Should().Be(_unencryptedKey);
         actual.IsParameterEncrypted.Should().BeFalse();
     }
 }
コード例 #17
0
ファイル: Startup.cs プロジェクト: spiir/client-managed-keys
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IKeyService, KeyService>();
            services.AddSingleton <IKeyProvider, DemoKeyProvider>();

            services
            .AddControllers()
            .AddJsonOptions(options =>
                            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverterWithAttributeSupport()));

            var authCert = new X509Certificate2(typeof(Startup).Assembly.GetResourceAsBytes("DemoAuthCert.der"));

            services
            .AddHttpMessageSignatureVerification(
                Client.Create(
                    "f011e0fca818d436a75abf878a31accf1e7d80d4",
                    "Nordic API Gateway 'Client Managed Keys' Test Client",
                    SignatureAlgorithm.CreateForVerification(authCert, HashAlgorithmName.SHA256)
                    )
                )
            .AddAuthentication(SignedHttpRequestDefaults.AuthenticationScheme)
            .AddSignedRequests();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "Client Managed Keys",
                    Version     = "v1",
                    Description = ReadDocumentationFile("README.md")
                });

                c.TagActionsBy(description => new List <string>()
                {
                    "Key operations"
                });

                c.SchemaFilter <DescribeEnumMemberValues>();

                c.AddSecurityDefinition("HTTP Signatures", new OpenApiSecurityScheme
                {
                    In          = ParameterLocation.Header,
                    Name        = "Authorization",
                    Type        = SecuritySchemeType.Http,
                    Description = ReadDocumentationFile("authentication.md")
                });

                var filePathServer = Path.Combine(AppContext.BaseDirectory, "ClientManagedKeys.Server.xml");
                var filePathModels = Path.Combine(AppContext.BaseDirectory, "ClientManagedKeys.Models.xml");

                c.IncludeXmlComments(filePathServer);
                c.IncludeXmlComments(filePathModels);
            });
        }
コード例 #18
0
 public void GivenHMACAlgorithm_ReturnsExpectedDataRecord()
 {
     using (var hmac = SignatureAlgorithm.CreateForVerification("s3cr3t", HashAlgorithmName.SHA384)) {
         var actual   = SignatureAlgorithmDataRecord.FromSignatureAlgorithm(hmac);
         var expected = new SignatureAlgorithmDataRecord {
             Type          = "HMAC",
             Parameter     = "s3cr3t",
             HashAlgorithm = HashAlgorithmName.SHA384.Name
         };
         actual.Should().BeEquivalentTo(expected);
     }
 }
コード例 #19
0
            public void GivenHMACAlgorithm_ReturnsExpectedDataRecord()
            {
                using (var hmac = SignatureAlgorithm.CreateForVerification(_unencryptedKey, HashAlgorithmName.SHA384)) {
                    _sut.SetSignatureAlgorithm(_dataRecord, hmac, _encryptionKey);

                    _dataRecord.SigType.Should().Be("HMAC");
                    _dataRecord.SigHashAlgorithm.Should().Be(HashAlgorithmName.SHA384.Name);
                    _dataRecord.IsSigParameterEncrypted.Should().BeTrue();
                    var encryptedKey = new FakeStringProtector().Protect(_unencryptedKey);
                    _dataRecord.SigParameter.Should().Be(encryptedKey);
                }
            }
コード例 #20
0
            public void GivenRSAAlgorithm_ReturnsExpectedDataRecord()
            {
                using (var rsa = new RSACryptoServiceProvider()) {
                    using (var rsaAlg = SignatureAlgorithm.CreateForVerification(rsa, HashAlgorithmName.SHA384)) {
                        _sut.SetSignatureAlgorithm(_dataRecord, rsaAlg, _encryptionKey);

                        _dataRecord.SigType.Should().Be("RSA");
                        _dataRecord.SigHashAlgorithm.Should().Be(HashAlgorithmName.SHA384.Name);
                        _dataRecord.IsSigParameterEncrypted.Should().BeFalse();
                        _dataRecord.SigParameter.Should().Be(rsa.ExportParameters(false).ToXml());
                    }
                }
            }
コード例 #21
0
            public void GivenECDsaAlgorithm_ReturnsExpectedDataRecord()
            {
                using (var ecdsa = ECDsa.Create()) {
                    using (var ecdsaAlg = SignatureAlgorithm.CreateForVerification(ecdsa, HashAlgorithmName.SHA384)) {
                        _sut.SetSignatureAlgorithm(_dataRecord, ecdsaAlg, _encryptionKey);

                        _dataRecord.SigType.Should().Be("ECDsa");
                        _dataRecord.SigHashAlgorithm.Should().Be(HashAlgorithmName.SHA384.Name);
                        _dataRecord.IsSigParameterEncrypted.Should().BeFalse();
                        _dataRecord.SigParameter.Should().Be(ecdsa.ExportParameters(false).ToXml());
                    }
                }
            }
コード例 #22
0
 public void GivenHMACAlgorithm_ReturnsExpectedDataRecord()
 {
     using (var hmac = SignatureAlgorithm.CreateForVerification(_unencryptedKey, HashAlgorithmName.SHA384)) {
         var actual   = SignatureAlgorithmDataRecordV2.FromSignatureAlgorithm(hmac, _encryptionKey);
         var expected = new SignatureAlgorithmDataRecordV2 {
             Type                 = "HMAC",
             HashAlgorithm        = HashAlgorithmName.SHA384.Name,
             IsParameterEncrypted = true
         };
         actual.Should().BeEquivalentTo(expected, opts => opts.Excluding(_ => _.Parameter));
         actual.Parameter.Should().NotBe(_unencryptedKey);
     }
 }
コード例 #23
0
 public void GivenRSAAlgorithm_ReturnsExpectedDataRecord()
 {
     using (var rsa = new RSACryptoServiceProvider()) {
         using (var rsaAlg = SignatureAlgorithm.CreateForVerification(rsa, HashAlgorithmName.SHA384)) {
             var actual   = SignatureAlgorithmDataRecord.FromSignatureAlgorithm(rsaAlg);
             var expected = new SignatureAlgorithmDataRecord {
                 Type          = "RSA",
                 Parameter     = rsa.ExportParameters(false).ToXml(),
                 HashAlgorithm = HashAlgorithmName.SHA384.Name
             };
             actual.Should().BeEquivalentTo(expected);
         }
     }
 }
コード例 #24
0
 public void GivenHMACAlgorithm_ReturnsExpectedDataRecord()
 {
     using (var hmac = SignatureAlgorithm.CreateForVerification(_unencryptedKey, HashAlgorithmName.SHA384)) {
         var actual       = _sut.FromSignatureAlgorithm(hmac, _encryptionKey);
         var encryptedKey = new FakeStringProtector().Protect(_unencryptedKey);
         var expected     = new SignatureAlgorithmDataRecordV2 {
             Type                 = "HMAC",
             HashAlgorithm        = HashAlgorithmName.SHA384.Name,
             IsParameterEncrypted = true,
             Parameter            = encryptedKey
         };
         actual.Should().BeEquivalentTo(expected);
     }
 }
コード例 #25
0
 public void GivenECDsaAlgorithm_ReturnsExpectedDataRecord()
 {
     using (var ecdsa = ECDsa.Create()) {
         using (var ecdsaAlg = SignatureAlgorithm.CreateForVerification(ecdsa, HashAlgorithmName.SHA384)) {
             var actual   = SignatureAlgorithmDataRecord.FromSignatureAlgorithm(ecdsaAlg);
             var expected = new SignatureAlgorithmDataRecord {
                 Type          = "ECDsa",
                 Parameter     = ecdsa.ExportParameters(false).ToXml(),
                 HashAlgorithm = HashAlgorithmName.SHA384.Name
             };
             actual.Should().BeEquivalentTo(expected);
         }
     }
 }
コード例 #26
0
 private static void ConfigureServices(IServiceCollection services)
 {
     services
     .AddHttpMessageSigning().Services
     .AddHttpMessageSignatureVerification()
     .UseAspNetCoreSignatureVerification()
     .UseClient(Client.Create(
                    "e0e8dcd638334c409e1b88daf821d135",
                    "HttpMessageSigningSampleHMAC",
                    SignatureAlgorithm.CreateForVerification("yumACY64r%hm"),
                    options => options.Claims = new [] {
         new Claim(SignedHttpRequestClaimTypes.Role, "users.read")
     }
                    ));;
 }
コード例 #27
0
 private static void ConfigureServices(IServiceCollection services)
 {
     services
     .AddHttpMessageSigning()
     .AddHttpMessageSignatureVerification(provider => {
         var clientStore = new InMemoryClientStore();
         clientStore.Register(new Client(
                                  new KeyId("e0e8dcd638334c409e1b88daf821d135"),
                                  "HttpMessageSigningSampleHMAC",
                                  SignatureAlgorithm.CreateForVerification("yumACY64r%hm"),
                                  TimeSpan.FromMinutes(5),
                                  TimeSpan.FromMinutes(1),
                                  new Claim(SignedHttpRequestClaimTypes.Role, "users.read")));
         return(clientStore);
     });
 }
            public async Task WhenSignatureVerificationFails_ReturnsNull()
            {
                _request.Headers["Authorization"] = "TestScheme abc123";

                var failureResult = new RequestSignatureVerificationResultFailure(
                    new Client("c1", "test", SignatureAlgorithm.CreateForVerification("s3cr3t"), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(1)),
                    new Signature(),
                    SignatureVerificationFailure.HeaderMissing("A header is missing.", null));

                A.CallTo(() => _options.RequestSignatureVerifier.VerifySignature(
                             A <IOwinRequest> .That.Matches(ConvertedRequest),
                             A <SignedHttpRequestAuthenticationOptions> ._))
                .Returns(failureResult);

                var actual = await _method();

                actual.Should().BeNull();
            }
コード例 #29
0
ファイル: Startup.cs プロジェクト: zacuke/HttpMessageSigning
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddRouting(options => { })
            .AddControllersWithViews().Services
            .AddAuthentication(SignedHttpRequestDefaults.AuthenticationScheme)
            .AddSignedRequests(options => {
                options.Realm = "Sample web application";
                options.OnIdentityVerified = (request, successResult) => {
                    var identity = (ClaimsIdentity)successResult.Principal.Identity;
                    Console.WriteLine("Identity '{0}' was authenticated by the request signature.", identity.Name ?? "[NULL]");
                    return(Task.CompletedTask);
                };
                options.OnIdentityVerificationFailed = (request, failure) => {
                    Console.WriteLine("The request signature could not be verified. Authentication failed: {0}", failure.Failure.Message);
                    return(Task.CompletedTask);
                };
            }).Services

            /* Sample for InMemoryClientStore */
            .AddHttpMessageSignatureVerification()
            .UseAspNetCoreSignatureVerification()
            .UseClient(
                Client.Create(
                    new KeyId("e0e8dcd638334c409e1b88daf821d135"),
                    "Sample client",
                    SignatureAlgorithm.CreateForVerification("G#6l$!D16E2UPoYKu&oL@AjAOj9vipKJTSII%*8iY*q6*MOis2R"),
                    options => options.Claims = new[] { new Claim(SignedHttpRequestClaimTypes.Role, "user.read") })
                )

            /* Sample for storing Clients and Nonces in MongoDB instead of in-memory */

            /*.UseMongoDbClientStore(provider => new MongoDbClientStoreSettings {
             *  ConnectionString = "mongodb://localhost:27017/HttpMessageSigningDb",
             *  CollectionName = "known_clients",
             *  ClientCacheEntryExpiration = TimeSpan.FromMinutes(3),
             *  SharedSecretEncryptionKey = "The_Big_S3cr37"
             * })
             * .UseMongoDbNonceStore(provider => new MongoDbNonceStoreSettings {
             *  ConnectionString = "mongodb://localhost:27017/HttpMessageSigningDb",
             *  CollectionName = "client_nonces"
             * })*/
            ;
        }
コード例 #30
0
        public VerifyRequestWithDigest()
        {
            var keyId           = new KeyId("e0e8dcd638334c409e1b88daf821d135");
            var serviceProvider = new ServiceCollection()
                                  .AddHttpMessageSigning(
                keyId,
                provider => new SigningSettings {
                SignatureAlgorithm  = SignatureAlgorithm.CreateForSigning("yumACY64r%hm"),
                DigestHashAlgorithm = HashAlgorithmName.SHA256,
                EnableNonce         = false,
                Expires             = TimeSpan.FromMinutes(1),
                Headers             = new [] {
                    (HeaderName)"Dalion-App-Id"
                }
            })
                                  .AddHttpMessageSignatureVerification(provider => {
                var clientStore = new InMemoryClientStore();
                clientStore.Register(new Client(
                                         new KeyId("e0e8dcd638334c409e1b88daf821d135"),
                                         "HttpMessageSigningSampleHMAC",
                                         SignatureAlgorithm.CreateForVerification("yumACY64r%hm"),
                                         TimeSpan.FromMilliseconds(1),
                                         TimeSpan.FromMinutes(1),
                                         new Claim(SignedHttpRequestClaimTypes.Role, "users.read")));
                return(clientStore);
            })
                                  .BuildServiceProvider();
            var requestSignerFactory = serviceProvider.GetRequiredService <IRequestSignerFactory>();
            var requestSigner        = requestSignerFactory.CreateFor(keyId);
            var request = new HttpRequestMessage {
                RequestUri = new Uri("https://httpbin.org/post"),
                Method     = HttpMethod.Post,
                Content    = new StringContent("{'id':42}", Encoding.UTF8, MediaTypeNames.Application.Json),
                Headers    =
                {
                    { "Dalion-App-Id", "ringor" }
                }
            };

            requestSigner.Sign(request).GetAwaiter().GetResult();
            _verifier = serviceProvider.GetRequiredService <IRequestSignatureVerifier>();
            _request  = request.ToServerSideHttpRequest().GetAwaiter().GetResult();
        }