public SignRequestWithDigest()
        {
            var keyId = new KeyId("e0e8dcd638334c409e1b88daf821d135");
            var cert  = new X509Certificate2(File.ReadAllBytes("./dalion.local.pfx"), "CertP@ss123", X509KeyStorageFlags.Exportable);

            var serviceProvider = new ServiceCollection()
                                  .AddHttpMessageSigning()
                                  .UseKeyId(keyId)
                                  .UseSignatureAlgorithm(SignatureAlgorithm.CreateForSigning("yumACY64r%hm"))
                                  .UseExpires(TimeSpan.FromMinutes(1))
                                  .UseHeaders((HeaderName)"Dalion-App-Id")
                                  .Services
                                  .BuildServiceProvider();
            var requestSignerFactory = serviceProvider.GetRequiredService <IRequestSignerFactory>();

            _requestSigner = requestSignerFactory.CreateFor(keyId);
            _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" }
                }
            };
        }
        public SignRequestWithDigest()
        {
            var keyId           = new KeyId("e0e8dcd638334c409e1b88daf821d135");
            var serviceProvider = new ServiceCollection()
                                  .AddHttpMessageSigning(
                keyId,
                provider => new SigningSettings {
                SignatureAlgorithm  = SignatureAlgorithm.CreateForSigning("yumACY64r%hm"),
                DigestHashAlgorithm = HashAlgorithmName.SHA256,
                EnableNonce         = true,
                Expires             = TimeSpan.FromMinutes(1),
                Headers             = new [] {
                    (HeaderName)"Dalion-App-Id"
                }
            })
                                  .BuildServiceProvider();
            var requestSignerFactory = serviceProvider.GetRequiredService <IRequestSignerFactory>();

            _requestSigner = requestSignerFactory.CreateFor(keyId);
            _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" }
                }
            };
        }
        /// <summary>
        /// Gets the authorization query for a signed request.
        /// </summary>
        /// <param name="signer">The request signer.</param>
        /// <param name='method'>HTTP request method.</param>
        /// <param name='uri'>The request resource URI.</param>
        /// <param name="options">The OAuth options.</param>
        /// <param name='parameters'>Request Parameters, see http://tools.ietf.org/html/rfc5849#section-3.4.1.3 </param>
        /// <param name="tokenCredentials">Token Credentials.</param>
        /// <returns>The authorization header.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static IDictionary <string, StringValues> AppendAuthorizationParameters(
            this IRequestSigner signer, HttpMethod method, Uri uri, OAuthOptions options,
            IDictionary <string, StringValues>?parameters = null, OAuthCredential?tokenCredentials = null)
        {
            if (signer == null)
            {
                throw new ArgumentNullException(nameof(signer));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            parameters ??= new Dictionary <string, StringValues>();
            if (tokenCredentials != null && !string.IsNullOrWhiteSpace(tokenCredentials.Value.Key))
            {
                parameters[OAuthDefaults.OAuthToken] = tokenCredentials.Value.Key;
            }

            parameters[OAuthDefaults.OAuthNonce]     = options.NonceProvider();
            parameters[OAuthDefaults.OAuthTimestamp] = options.TimestampProvider();
            if (options.ProvideVersion)
            {
                parameters[OAuthDefaults.OAuthVersion] = OAuthDefaults.Version1;
            }
            parameters[OAuthDefaults.OAuthConsumerKey]     = options.ClientCredentials.Key;
            parameters[OAuthDefaults.OAuthSignatureMethod] = signer.MethodName;
            parameters[OAuthDefaults.OAuthSignature]       = signer.GetSignature(method, uri, parameters, options.ClientCredentials.Secret, tokenCredentials?.Secret);
            return(parameters);
        }
        /// <summary>
        /// Gets the authorization header for a signed request.
        /// </summary>
        /// <param name="signer">The request signer.</param>
        /// <param name='method'>HTTP request method.</param>
        /// <param name='uri'>The request resource URI.</param>
        /// <param name="options">The OAuth options.</param>
        /// <param name='parameters'>Request Parameters, see http://tools.ietf.org/html/rfc5849#section-3.4.1.3 </param>
        /// <param name="tokenCredentials">Token Credentials.</param>
        /// <returns>The authorization header.</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static AuthenticationHeaderValue GetAuthorizationHeader(this IRequestSigner signer,
                                                                       HttpMethod method,
                                                                       Uri uri,
                                                                       OAuthOptions options,
                                                                       IDictionary <string, StringValues>?parameters = null,
                                                                       OAuthCredential?tokenCredentials = null)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            var query  = AppendAuthorizationParameters(signer, method, uri, options, parameters, tokenCredentials);
            var values = new List <string>();

            foreach (var entry in query.Where(p => p.Key.StartsWith(OAuthDefaults.OAuthPrefix, StringComparison.Ordinal)))
            {
                foreach (var value in entry.Value)
                {
                    values.Add($"{options.PercentEncoder(entry.Key)}=\"{options.PercentEncoder(value)}\"");
                }
            }
            var headerValue = string.Join(",", values);

            if (options.Realm != null && !string.IsNullOrWhiteSpace(options.Realm))
            {
                return(new AuthenticationHeaderValue(OAuthDefaults.OAuthScheme, $"{OAuthDefaults.Realm}=\"{options.PercentEncoder(options.Realm)}\",{headerValue}"));
            }
            return(new AuthenticationHeaderValue(OAuthDefaults.OAuthScheme, headerValue));
        }
Exemplo n.º 5
0
 internal BlueClient(ILogger <BlueClient> logger, IHttpClientProducer httpClientProducer, IRequestSigner requestSigner)
 {
     _logger             = logger;
     _httpClientProducer = httpClientProducer;
     _requestSigner      = requestSigner;
     _serializer         = new JsonSerializer();
 }
 public OAuthHttpHandler(IOptions <OAuthHttpHandlerOptions> options, IRequestSigner signer)
 {
     if (options == null)
     {
         throw new ArgumentNullException(nameof(options));
     }
     _options = options.Value;
     _signer  = signer;
 }
Exemplo n.º 7
0
 internal BlueClient(ILogger <BlueClient> logger, IHttpClientProducer httpClientProducer, IRequestSigner requestSigner)
 {
     _logger             = logger;
     _httpClientProducer = httpClientProducer;
     _requestSigner      = requestSigner;
     _serializer         = JsonSerializer.Create(new JsonSerializerSettings
     {
         NullValueHandling = NullValueHandling.Ignore
     });
 }
Exemplo n.º 8
0
 public RestClient(IRestTransport transport,
                   string baseUrl        = "",
                   IRequestSigner signer = null,
                   ReadOnlyHttpHeaders defaultHeaders = null,
                   ReadOnlyHttpCookies defaultCookies = null)
 {
     Transport      = transport;
     BaseUrl        = baseUrl;
     Signer         = signer ?? new UnitRequestSigner();
     DefaultHeaders = defaultHeaders ?? new ReadOnlyDictionary <string, string>(NoHeaders);
     DefaultCookies = defaultCookies ?? new ReadOnlyDictionary <string, string>(NoCookies);
 }
Exemplo n.º 9
0
 protected AuthorizerBase(
     IOptions <AuthorizerOptions> options,
     HttpClient httpClient,
     IRequestSigner signer)
 {
     if (options == null)
     {
         throw new ArgumentNullException(nameof(options));
     }
     _options    = options.Value;
     _httpClient = httpClient;
     _signer     = signer;
 }
 // This is for asserting inside a request like this:
 // InRequest(
 //     rest => rest.Get(url),                    // <- perform a rest call
 //     "<html><head>...",                        // <- respond with this content
 //     req => Assert.Equal(url, req.RequestUri)  // <- verify that the request is as expected
 // );
 internal static void InRequest(Action <RestClient> restCall,
                                string responseContent,
                                IRequestSigner signer,
                                IReadOnlyDictionary <string, string> defaultHeaders,
                                IReadOnlyDictionary <string, string> defaultCookies,
                                Action <HttpRequestMessage> assertRequest)
 {
     using var transport = new RestTransport(request =>
     {
         assertRequest(request);
         return(RespondWith(responseContent, NoHeaders)(request));
     });
     restCall(new RestClient(transport, "", signer, defaultHeaders, defaultCookies));
 }
 /// <summary>
 ///     Create a new instance of this class.
 /// </summary>
 /// <param name="requestSigner">The <see cref="IRequestSigner" /> that will sign the request.</param>
 public HttpRequestSigningHandler(IRequestSigner requestSigner)
 {
     _requestSigner = requestSigner ?? throw new ArgumentNullException(nameof(requestSigner));
 }
 public AddressResolver(IMasterServiceIdentityProvider masterServiceIdentityProvider, IRequestSigner requestSigner, string location)
 {
     this.masterServiceIdentityProvider = masterServiceIdentityProvider;
     this.requestSigner = requestSigner;
     this.location      = location;
 }
 public InteractiveConsoleAuthorizer(IOptions <AuthorizerOptions> options, HttpClient httpClient, IRequestSigner signer) : base(options, httpClient, signer)
 {
 }
 public AddressResolver(ServiceIdentity masterServiceIdentity, IRequestSigner requestSigner, string location)
 {
     this.masterServiceIdentity = masterServiceIdentity;
     this.requestSigner         = requestSigner;
     this.location = location;
 }
 public BlueClientBuilder UseUsernamePassword(string username, string password)
 {
     _requestSigner = new UsernamePasswordRequestSigner(username, password);
     return(this);
 }
 internal static void InRequest(Action <RestClient> restCall,
                                IRequestSigner signer,
                                Action <HttpRequestMessage> assertRequest)
 {
     InRequest(restCall, "", signer, NoHeaders, NoCookies, assertRequest);
 }
Exemplo n.º 17
0
 public FakeAuthorizer(IOptions <AuthorizerOptions> options, HttpClient httpClient, IRequestSigner signer) : base(
         options, httpClient, signer)
 {
 }