예제 #1
0
        public async Task <IActionResult> PostRevoke(
            [FromForm] RevocationRequest revocationRequest,
            CancellationToken cancellationToken)
        {
            // 1. Fetch the authorization header
            AuthenticationHeaderValue?authenticationHeaderValue = null;

            if (Request.Headers.TryGetValue(HeaderNames.Authorization, out var authorizationHeader))
            {
                var authorizationHeaderValue         = authorizationHeader.First();
                var splittedAuthorizationHeaderValue = authorizationHeaderValue.Split(' ');
                if (splittedAuthorizationHeaderValue.Length == 2)
                {
                    authenticationHeaderValue = new AuthenticationHeaderValue(
                        splittedAuthorizationHeaderValue[0],
                        splittedAuthorizationHeaderValue[1]);
                }
            }

            // 2. Revoke the token
            var issuerName = Request.GetAbsoluteUriWithVirtualPath();
            var option     = await _tokenActions.RevokeToken(
                revocationRequest.ToParameter(),
                authenticationHeaderValue,
                Request.GetCertificate(),
                issuerName,
                cancellationToken)
                             .ConfigureAwait(false);

            return(option switch
            {
                Option.Success => new OkResult(),
                Option.Error e => BadRequest(e.Details),
                _ => throw new ArgumentOutOfRangeException()
            });
        /// <summary>
        /// Check the parameters based on the RFC : http://openid.net/specs/openid-connect-core-1_0.html#TokenRequestValidation
        /// </summary>
        /// <param name="authorizationCodeGrantTypeParameter"></param>
        /// <param name="authenticationHeaderValue"></param>
        /// <param name="certificate"></param>
        /// <param name="issuerName"></param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the async operation.</param>
        /// <returns></returns>
        private async Task <Option <ValidationResult> > ValidateParameter(
            AuthorizationCodeGrantTypeParameter authorizationCodeGrantTypeParameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            if (authorizationCodeGrantTypeParameter.Code == null)
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidGrant,
                    Detail = Strings.TheAuthorizationCodeIsNotCorrect
                });
            }

            // 1. Authenticate the client
            var instruction = authenticationHeaderValue.GetAuthenticateInstruction(
                authorizationCodeGrantTypeParameter,
                certificate);
            var authResult = await _authenticateClient.Authenticate(instruction, issuerName, cancellationToken)
                             .ConfigureAwait(false);

            var client = authResult.Client;

            if (client == null)
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidClient,
                    Detail = authResult.ErrorMessage !
                });
예제 #3
0
        public async Task <Option <GrantedToken> > GetTokenByTicketId(
            GetTokenViaTicketIdParameter parameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(parameter.Ticket))
            {
                _logger.LogError("Ticket is null or empty");
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(Strings.MissingParameter, UmaConstants.RptClaims.Ticket)
                });
            }

            var instruction = authenticationHeaderValue.GetAuthenticateInstruction(parameter, certificate);
            var authResult  = await _authenticateClient.Authenticate(instruction, issuerName, cancellationToken)
                              .ConfigureAwait(false);

            var client = authResult.Client;

            if (client == null)
            {
                _logger.LogError("Client not found.");
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidClient,
                    Detail = authResult.ErrorMessage !
                });
        public async Task <TResult?> ExecuteApi <TResult>(HttpMethod method, string resourcePath,
                                                          AuthenticationHeaderValue?authenticationHeader = null,
                                                          object?data = null) where TResult : class
        {
            var url = GetUrl(resourcePath);
            var httpRequestMessage = new HttpRequestMessage(method, url);

            try
            {
                httpRequestMessage = AddDefaultHeaders(httpRequestMessage);
                httpRequestMessage = AddStringContent(httpRequestMessage, data);
                httpRequestMessage = AddAuthenticationHeader(httpRequestMessage, authenticationHeader);


                var httpResponse = await _client.SendAsync(httpRequestMessage);

                var resultContent = await httpResponse.Content.ReadAsStringAsync();

                if (httpResponse.IsSuccessStatusCode)
                {
                    if (string.IsNullOrWhiteSpace(resultContent))
                    {
                        return new ErrorResult {
                                   IsSuccessStatusCode = false
                        }
                    }
                    as TResult;

                    var result =
                        JsonConvert.DeserializeObject <TResult?>(resultContent, JsonUtils.StringEnumJsonSerializerSettings);

                    return(result);
                }
예제 #5
0
        public async Task <Option <GrantedToken> > GetTokenByClientCredentialsGrantType(
            ClientCredentialsGrantTypeParameter clientCredentialsGrantTypeParameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(clientCredentialsGrantTypeParameter.Scope))
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(Strings.MissingParameter, StandardTokenRequestParameterNames.ScopeName)
                });
            }

            // 1. Authenticate the client
            var instruction = authenticationHeaderValue.GetAuthenticateInstruction(
                clientCredentialsGrantTypeParameter,
                certificate);
            var authResult = await _authenticateClient.Authenticate(instruction, issuerName, cancellationToken)
                             .ConfigureAwait(false);

            var client = authResult.Client;

            if (client == null)
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidClient,
                    Detail = authResult.ErrorMessage !
                });
예제 #6
0
        public async Task <Option <GrantedToken> > GetTokenByRefreshTokenGrantType(
            RefreshTokenGrantTypeParameter refreshTokenGrantTypeParameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            // Read this RFC for more information
            if (string.IsNullOrWhiteSpace(refreshTokenGrantTypeParameter.RefreshToken))
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(
                        Strings.MissingParameter,
                        StandardTokenRequestParameterNames.RefreshToken)
                });
            }

            return(await _getTokenByRefreshTokenGrantTypeAction.Execute(
                       refreshTokenGrantTypeParameter,
                       authenticationHeaderValue,
                       certificate,
                       issuerName,
                       cancellationToken).ConfigureAwait(false));
        }
예제 #7
0
        /// <summary>
        /// Gets the result of the <see cref="HttpRequestMessage"/>.
        /// </summary>
        /// <typeparam name="T">The <see cref="Type"/> of data downloaded.</typeparam>
        /// <param name="request">The download request.</param>
        /// <param name="token">The authorization token for the request.</param>
        /// <param name="certificate">The <see cref="X509Certificate2"/> to include in request.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the async operation.</param>
        /// <returns></returns>
        protected async Task <Option <T> > GetResult <T>(
            HttpRequestMessage request,
            AuthenticationHeaderValue?token,
            X509Certificate2?certificate        = null,
            CancellationToken cancellationToken = default)
            where T : class
        {
            request = PrepareRequest(request, token, certificate);
            var result = await _client().SendAsync(request, cancellationToken).ConfigureAwait(false);

#if NET5_0
            var content = await result.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
#else
            var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
#endif
            if (result.IsSuccessStatusCode && result.StatusCode != HttpStatusCode.NoContent)
            {
                return(Serializer.Default.Deserialize <T>(content) !);
            }

            var genericResult = string.IsNullOrWhiteSpace(content)
                ? new ErrorDetails {
                Status = result.StatusCode
            }
                : Serializer.Default.Deserialize <ErrorDetails>(content);

            return(genericResult !);
        }
예제 #8
0
        public static AuthenticateInstruction GetAuthenticateInstruction(
            this AuthenticationHeaderValue?authenticationHeaderValue,
            GrantTypeParameter?grantTypeParameter,
            X509Certificate2?certificate = null)
        {
            var result = grantTypeParameter == null
                ? new AuthenticateInstruction {
                Certificate = certificate
            }
                : new AuthenticateInstruction
            {
                ClientAssertion                 = grantTypeParameter.ClientAssertion,
                ClientAssertionType             = grantTypeParameter.ClientAssertionType,
                ClientIdFromHttpRequestBody     = grantTypeParameter.ClientId,
                ClientSecretFromHttpRequestBody = grantTypeParameter.ClientSecret,
                Certificate = certificate
            };

            if (authenticationHeaderValue == null)
            {
                return(result);
            }
            if (!string.IsNullOrWhiteSpace(authenticationHeaderValue.Parameter) && string.Equals(authenticationHeaderValue.Scheme, "Basic", StringComparison.OrdinalIgnoreCase))
            {
                var parameters = GetParameters(authenticationHeaderValue.Parameter);
                if (parameters.Length == 2)
                {
                    result.ClientIdFromAuthorizationHeader     = parameters[0];
                    result.ClientSecretFromAuthorizationHeader = parameters[1];
                }
            }

            return(result);
        }
예제 #9
0
        public async Task <Option> Execute(
            RevokeTokenParameter revokeTokenParameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            var refreshToken = revokeTokenParameter.Token;

            if (refreshToken == null)
            {
                _logger.LogError(Strings.TheRefreshTokenIsNotValid);
                return(new ErrorDetails
                {
                    Detail = Strings.TheRefreshTokenIsNotValid,
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidToken
                });
            }
            // 1. Check the client credentials
            var instruction = authenticationHeaderValue.GetAuthenticateInstruction(revokeTokenParameter, certificate);
            var authResult  = await _authenticateClient.Authenticate(instruction, issuerName, cancellationToken)
                              .ConfigureAwait(false);

            var client = authResult.Client;

            if (client == null)
            {
                _logger.LogError(authResult.ErrorMessage);
                return(new ErrorDetails
                {
                    Detail = authResult.ErrorMessage !,
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidClient
                });
예제 #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TokenClient"/> class.
 /// </summary>
 /// <param name="credentials">The <see cref="TokenCredentials"/>.</param>
 /// <param name="client">The <see cref="HttpClient"/> for requests.</param>
 /// <param name="discoveryDocumentation">The metadata information.</param>
 public TokenClient(TokenCredentials credentials, Func <HttpClient> client, DiscoveryInformation discoveryDocumentation)
     : base(client)
 {
     _form               = credentials;
     _client             = client;
     _authorizationValue = credentials.AuthorizationValue;
     _certificate        = credentials.Certificate;
     _discovery          = discoveryDocumentation;
 }
        public async Task <List <HelixGameRecord> > GetGameByIdAsync(string id,
                                                                     AuthenticationHeaderValue?authentication = null,
                                                                     CancellationToken cancelToken            = default)
        {
            var response = await GetDataResponseAsync <HelixGameRecord>(
                Endpoints.Games,
                new[] { new KeyValuePair <string, string>(nameof(id), id) },
                authentication, cancelToken).ConfigureAwait(false);

            return(response.Data);
        }
        public async Task <List <HelixGameRecord> > GetGamesByIdsAsync(
            IEnumerable <string> ids,
            AuthenticationHeaderValue?authentication = null,
            CancellationToken cancelToken            = default)
        {
            var response = await GetDataResponseAsync <HelixGameRecord>(
                Endpoints.Games,
                ids.Select(id => new KeyValuePair <string, string>(nameof(id), id)),
                authentication, cancelToken).ConfigureAwait(false);

            return(response.Data);
        }
        public static bool TryParse([NotNullWhen(true)] string?input, [NotNullWhen(true)] out AuthenticationHeaderValue?parsedValue)
        {
            int index = 0;

            parsedValue = null;

            if (GenericHeaderParser.SingleValueAuthenticationParser.TryParseValue(input, null, ref index, out object?output))
            {
                parsedValue = (AuthenticationHeaderValue)output !;
                return(true);
            }
            return(false);
        }
        public void NullAuthenticationHeaderValue()
        {
            //Arrange
            var services           = new ServiceCollection();
            var productHeaderValue = GetProductHeaderValue();
            AuthenticationHeaderValue?authenticationHeaderValue = null;

            //Act

            //Assett
#pragma warning disable CS8604 // Possible null reference argument.
            Assert.Throws <ArgumentNullException>(() => services.AddGitHubApiStatusService(authenticationHeaderValue, productHeaderValue));
#pragma warning restore CS8604 // Possible null reference argument.
        }
            static HttpRequestMessage CreateRequest(Uri requestUri,
                                                    string?clientId, AuthenticationHeaderValue?authentication)
            {
                var msg = new HttpRequestMessage(HttpMethod.Get, requestUri);

                if (!(authentication is null))
                {
                    msg.Headers.Authorization = authentication;
                }
                if (!(clientId is null))
                {
                    msg.Headers.Add(HelixApiDefaults.ClientIdHeaderName, clientId);
                }
                return(msg);
            }
예제 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TokenClient"/> class.
        /// </summary>
        /// <param name="credentials">The <see cref="TokenCredentials"/>.</param>
        /// <param name="client">The <see cref="HttpClient"/> for requests.</param>
        /// <param name="authority">The <see cref="Uri"/> of the discovery document.</param>
        public TokenClient(TokenCredentials credentials, Func <HttpClient> client, Uri authority)
            : base(client)
        {
            if (!authority.IsAbsoluteUri)
            {
                throw new ArgumentException(
                          string.Format(ClientStrings.TheUrlIsNotWellFormed, authority));
            }

            _form               = credentials;
            _client             = client;
            _authorizationValue = credentials.AuthorizationValue;
            _certificate        = credentials.Certificate;
            _discoveryOperation = new GetDiscoveryOperation(authority, client);
        }
예제 #17
0
        public async Task <IActionResult> PostToken(
            [FromForm] TokenRequest tokenRequest,
            CancellationToken cancellationToken)
        {
            var certificate = Request.GetCertificate();

            if (tokenRequest.grant_type == null)
            {
                return(BadRequest(
                           new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(Strings.MissingParameter, RequestTokenNames.GrantType)
                }));
            }

            AuthenticationHeaderValue?authenticationHeaderValue = null;

            if (Request.Headers.TryGetValue(HeaderNames.Authorization, out var authorizationHeader))
            {
                _ = AuthenticationHeaderValue.TryParse(authorizationHeader[0], out authenticationHeaderValue);
            }

            var issuerName = Request.GetAbsoluteUriWithVirtualPath();
            var result     = await GetGrantedToken(
                tokenRequest,
                authenticationHeaderValue,
                certificate,
                issuerName,
                cancellationToken)
                             .ConfigureAwait(false);

            if (result is Option <GrantedToken> .Result r)
            {
                return(new OkObjectResult(r.Item.ToDto()));
            }

            var e = (Option <GrantedToken> .Error)result;

            _logger.LogError(
                "Could not issue token. {0} - {1} - {2}",
                e.Details.Title,
                e.Details.Detail,
                e.Details.Status);

            return(new BadRequestObjectResult(e.Details));
        }
예제 #18
0
        private static HttpRequestMessage PrepareRequest(
            HttpRequestMessage request,
            AuthenticationHeaderValue?authorizationHeaderValue,
            X509Certificate2?certificate = null)
        {
            request.Headers.Accept.Clear();
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(JsonMimeType));
            request.Headers.Authorization = authorizationHeaderValue;

            if (certificate != null)
            {
                var base64Encoded = Convert.ToBase64String(certificate.RawData);
                request.Headers.Add("X-ARR-ClientCert", base64Encoded);
            }

            return(request);
        }
예제 #19
0
        public async Task <Option <GrantedToken> > GetTokenByResourceOwnerCredentialsGrantType(
            ResourceOwnerGrantTypeParameter resourceOwnerGrantTypeParameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            if (string.IsNullOrWhiteSpace(resourceOwnerGrantTypeParameter.UserName))
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(Strings.MissingParameter, StandardTokenRequestParameterNames.UserName)
                });
            }

            if (string.IsNullOrWhiteSpace(resourceOwnerGrantTypeParameter.Password))
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(
                        Strings.MissingParameter,
                        StandardTokenRequestParameterNames.PasswordName)
                });
            }

            if (string.IsNullOrWhiteSpace(resourceOwnerGrantTypeParameter.Scope))
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidRequest,
                    Detail = string.Format(Strings.MissingParameter, StandardTokenRequestParameterNames.ScopeName)
                });
            }

            return(await _getTokenByResourceOwnerCredentialsGrantType.Execute(
                       resourceOwnerGrantTypeParameter,
                       authenticationHeaderValue,
                       certificate,
                       issuerName,
                       cancellationToken).ConfigureAwait(false));
        }
        private async Task <JObject> GetDataResponseJObjectAsync(Uri requestUri,
                                                                 AuthenticationHeaderValue?authentication = null,
                                                                 CancellationToken cancelToken            = default)
        {
            using (var reqMsg = CreateRequest(requestUri, ClientId, authentication))
                using (var respMsg = await httpClient.SendAsync(reqMsg, cancelToken)
                                     .ConfigureAwait(continueOnCapturedContext: false))
                {
                    if (!respMsg.Content.IsJson() && !respMsg.Content.IsText())
                    {
                        throw new HttpRequestException($"Invalid Content-Type in response body: {respMsg.Content.Headers.ContentType}");
                    }
                    using var respTxtReader = await respMsg.Content
                                              .ReadAsStreamReaderAsync().ConfigureAwait(false);

                    using var respJsonReader = new JsonTextReader(respTxtReader);
                    return(await JObject.LoadAsync(respJsonReader, cancelToken)
                           .ConfigureAwait(continueOnCapturedContext: false));
                }
        public override bool Equals(object?obj)
        {
            AuthenticationHeaderValue?other = obj as AuthenticationHeaderValue;

            if (other == null)
            {
                return(false);
            }

            if (string.IsNullOrEmpty(_parameter) && string.IsNullOrEmpty(other._parameter))
            {
                return(string.Equals(_scheme, other._scheme, StringComparison.OrdinalIgnoreCase));
            }
            else
            {
                // Since we can't parse the parameter, we use case-sensitive comparison.
                return(string.Equals(_scheme, other._scheme, StringComparison.OrdinalIgnoreCase) &&
                       string.Equals(_parameter, other._parameter, StringComparison.Ordinal));
            }
        }
예제 #22
0
        /// <inheritdoc />
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var now = DateTimeOffset.Now;

            if (_authorizedUris == null)
            {
                throw new InvalidOperationException($"The '{nameof(CustomAuthorizationMessageHandler)}' is not configured. " +
                                                    $"Call '{nameof(CustomAuthorizationMessageHandler.ConfigureHandler)}' and provide a list of endpoint urls to attach the token to.");
            }

            if (_authorizedUris.Any(uri => uri.IsBaseOf(request.RequestUri !)))
            {
                if (_lastToken == null || now >= _lastToken.Expires.AddMinutes(-5))
                {
                    var tokenResult = _tokenOptions != null ?
                                      await _provider.RequestAccessToken(_tokenOptions) :
                                      await _provider.RequestAccessToken();

                    if (tokenResult.TryGetToken(out var token))
                    {
                        _lastToken    = token;
                        _cachedHeader = new AuthenticationHeaderValue("Bearer", _lastToken.Value);
                    }
                    else
                    {
                        _lastToken    = null;
                        _cachedHeader = null;
                    }
                }

                if (_cachedHeader != null)
                {
                    // We don't try to handle 401s and retry the request with a new token automatically since that would mean we need to copy the request
                    // headers and buffer the body and we expect that the user instead handles the 401s. (Also, we can't really handle all 401s as we might
                    // not be able to provision a token without user interaction).
                    request.Headers.Authorization = _cachedHeader;
                }
            }

            return(await base.SendAsync(request, cancellationToken));
        }
예제 #23
0
        public async Task <Option <GrantedToken> > GetTokenByAuthorizationCodeGrantType(
            AuthorizationCodeGrantTypeParameter authorizationCodeGrantTypeParameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            var validation = Validate(authorizationCodeGrantTypeParameter);

            if (validation is Option.Error e)
            {
                return(e.Details);
            }

            return(await _getTokenByAuthorizationCodeGrantTypeAction.Execute(
                       authorizationCodeGrantTypeParameter,
                       authenticationHeaderValue,
                       certificate,
                       issuerName,
                       cancellationToken).ConfigureAwait(false));
        }
    private async Task <OAuthToken> GetOAuthTokenAsync(HttpResponseMessage response, HttpRequestMessage unauthorizedRequest, CancellationToken cancellationToken = default)
    {
        AuthenticationHeaderValue?bearerHeader = response.Headers.WwwAuthenticate
                                                 .AsEnumerable()
                                                 .FirstOrDefault(header => header.Scheme == HttpBearerChallenge.Bearer);

        if (bearerHeader is null)
        {
            throw new AuthenticationException($"Bearer header not contained in unauthorized response from {response.RequestMessage?.RequestUri}");
        }

        HttpBearerChallenge challenge = HttpBearerChallenge.Parse(bearerHeader.Parameter);

        Uri authenticateUri = new($"{challenge.Realm}?service={challenge.Service}&scope={challenge.Scope}");
        HttpRequestMessage authenticateRequest = new(HttpMethod.Get, authenticateUri);

        authenticateRequest.Headers.Authorization = unauthorizedRequest.Headers.Authorization;

        cancellationToken.ThrowIfCancellationRequested();
        response = await base.SendAsync(authenticateRequest, cancellationToken).ConfigureAwait(false);

        response.EnsureSuccessStatusCode();

        cancellationToken.ThrowIfCancellationRequested();

#if NET5_0_OR_GREATER
        string tokenContent = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
#else
        string tokenContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
#endif

        try
        {
            return(SafeJsonConvert.DeserializeObject <OAuthToken>(tokenContent));
        }
        catch (JsonException e)
        {
            throw new SerializationException("Unable to deserialize the response.", tokenContent, e);
        }
    }
예제 #25
0
        public async Task <Option <GrantedToken> > Execute(
            RefreshTokenGrantTypeParameter refreshTokenGrantTypeParameter,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            // 1. Try to authenticate the client
            var instruction = authenticationHeaderValue.GetAuthenticateInstruction(
                refreshTokenGrantTypeParameter,
                certificate);
            var authResult = await _authenticateClient.Authenticate(instruction, issuerName, cancellationToken)
                             .ConfigureAwait(false);

            var client = authResult.Client;

            if (client == null)
            {
                return(new ErrorDetails
                {
                    Status = HttpStatusCode.BadRequest,
                    Title = ErrorCodes.InvalidClient,
                    Detail = authResult.ErrorMessage !
                });
예제 #26
0
 private TokenCredentials(Dictionary <string, string> form, AuthenticationHeaderValue?authorizationValue = null, X509Certificate2?certificate = null)
 {
     _form = form;
     AuthorizationValue = authorizationValue;
     Certificate        = certificate;
 }
예제 #27
0
        public static string DownloadToString(this IHttpChannel channel, string url, Encoding?encoding = default, AuthenticationHeaderValue?authenticationHeaderValue = null)
        {
            encoding = encoding ?? Encoding.UTF8;
            var request = channel.CreateRequest(url);

            if (authenticationHeaderValue != null)
            {
                request.Headers.Authorization = authenticationHeaderValue;
            }
            var result          = SharedHttpClient.Value.SendAsync(request).Result;
            var contentAsString = result.Content.ReadAsStringAsync().Result;

            return(contentAsString);
        }
예제 #28
0
        public static IHttpHeader DownloadHeader(this IHttpChannel channel, string url, AuthenticationHeaderValue?authenticationHeaderValue = null)
        {
            var request = channel.CreateRequest(url);

            if (authenticationHeaderValue != null)
            {
                request.Headers.Authorization = authenticationHeaderValue;
            }

            request.Method = HttpMethod.Head;

            var result = SharedHttpClient.Value.SendAsync(request).Result;

            var dict = result.Headers.ToDictionary(key => key.Key, v => v.Value.ToString() ?? "");

            return(new HttpHeader(dict));
        }
예제 #29
0
 public DefaultHttpAuthHeaderFactory(AuthenticationHeaderValue?authHeader)
 {
     this.authHeaderFunc = () => Task.FromResult(authHeader);
 }
예제 #30
0
        private async Task <Option <GrantedToken> > GetGrantedToken(
            TokenRequest tokenRequest,
            AuthenticationHeaderValue?authenticationHeaderValue,
            X509Certificate2?certificate,
            string issuerName,
            CancellationToken cancellationToken)
        {
            switch (tokenRequest.grant_type)
            {
            case GrantTypes.Device:
                return(await _tokenActions.GetTokenByDeviceGrantType(
                           tokenRequest.client_id,
                           tokenRequest.device_code,
                           issuerName,
                           cancellationToken).ConfigureAwait(false));

            case GrantTypes.Password:
                var resourceOwnerParameter = tokenRequest.ToResourceOwnerGrantTypeParameter();
                return(await _tokenActions.GetTokenByResourceOwnerCredentialsGrantType(
                           resourceOwnerParameter,
                           authenticationHeaderValue,
                           certificate,
                           issuerName,
                           cancellationToken)
                       .ConfigureAwait(false));

            case GrantTypes.AuthorizationCode:
                var authCodeParameter = tokenRequest.ToAuthorizationCodeGrantTypeParameter();
                return(await _tokenActions.GetTokenByAuthorizationCodeGrantType(
                           authCodeParameter,
                           authenticationHeaderValue,
                           certificate,
                           issuerName,
                           cancellationToken)
                       .ConfigureAwait(false));

            case GrantTypes.RefreshToken:
                var refreshTokenParameter = tokenRequest.ToRefreshTokenGrantTypeParameter();
                return(await _tokenActions.GetTokenByRefreshTokenGrantType(
                           refreshTokenParameter,
                           authenticationHeaderValue,
                           certificate,
                           issuerName,
                           cancellationToken)
                       .ConfigureAwait(false));

            case GrantTypes.ClientCredentials:
                var clientCredentialsParameter = tokenRequest.ToClientCredentialsGrantTypeParameter();
                return(await _tokenActions.GetTokenByClientCredentialsGrantType(
                           clientCredentialsParameter,
                           authenticationHeaderValue,
                           certificate,
                           issuerName,
                           cancellationToken)
                       .ConfigureAwait(false));

            case GrantTypes.UmaTicket:
                var tokenIdParameter = tokenRequest.ToTokenIdGrantTypeParameter();

                return(await _umaTokenActions.GetTokenByTicketId(
                           tokenIdParameter,
                           authenticationHeaderValue,
                           certificate,
                           issuerName,
                           cancellationToken)
                       .ConfigureAwait(false));

            case GrantTypes.ValidateBearer:
            //return null;
            default:
                throw new ArgumentOutOfRangeException(nameof(tokenRequest));
            }
        }