Example #1
0
        /// <summary>
        /// Hack to parse out the config types, won't be needed after api configuration
        /// </summary>
        /// <param name="configurationSection"></param>
        /// <returns></returns>
        public static OidcAuthenticationConfig ParseOidcAuthenticationConfig(IConfiguration configurationSection)
        {
            var oauthAuthenticationConfig = new OidcAuthenticationConfig
            {
                ClientId     = configurationSection["clientid"],
                ClientSecret = configurationSection["clientsecret"],
                Uri          = configurationSection["uri"],
                Scopes       = configurationSection["scopes"].Split(" ")
            };

            var refresh = configurationSection["refresh"];

            if (string.IsNullOrWhiteSpace(refresh))
            {
                oauthAuthenticationConfig.RefreshBeforeInSeconds = 10;
            }
            else
            {
                if (int.TryParse(refresh, out var refreshValue))
                {
                    oauthAuthenticationConfig.RefreshBeforeInSeconds = refreshValue;
                }
            }

            return(oauthAuthenticationConfig);
        }
        public async Task AuthorisationTokenSuccess(string expectedAccessToken)
        {
            var config = new OidcAuthenticationConfig
            {
                ClientId     = "bob",
                ClientSecret = "bobsecret",
                Scopes       = new[] { "bob.scope.all" },
                Uri          = "http://localhost/authendpoint"
            };

            var handler = new OidcAuthenticationHandler(config);

            var mockHttp    = new MockHttpMessageHandler(BackendDefinitionBehavior.Always);
            var mockRequest = mockHttp.When(HttpMethod.Post, config.Uri)
                              .WithFormData("client_id", config.ClientId)
                              .WithFormData("client_secret", config.ClientSecret)
                              .Respond(HttpStatusCode.OK, "application/json",
                                       JsonConvert.SerializeObject(new OidcAuthenticationToken
            {
                AccessToken = "6015CF7142BA060F5026BE9CC442C12ED7F0D5AECCBAA0678DEEBC51C6A1B282"
            }));

            var httpClient = mockHttp.ToHttpClient();

            await handler.GetToken(httpClient);

            Assert.Equal(1, mockHttp.GetMatchCount(mockRequest));
            Assert.NotNull(httpClient.DefaultRequestHeaders.Authorization);
            Assert.Equal(expectedAccessToken, httpClient.DefaultRequestHeaders.Authorization.Parameter);
            Assert.Equal("Bearer", httpClient.DefaultRequestHeaders.Authorization.Scheme);
        }
        public async Task RefreshToken(int refreshBeforeInSeconds, int expiryTimeInSeconds, int expectedStsCallCount)
        {
            var config = new OidcAuthenticationConfig
            {
                ClientId               = "bob",
                ClientSecret           = "bobsecret",
                Scopes                 = new[] { "bob.scope.all" },
                Uri                    = "http://localhost/authendpoint",
                RefreshBeforeInSeconds = refreshBeforeInSeconds
            };

            var handler = new OidcAuthenticationHandler(config);

            var mockHttp    = new MockHttpMessageHandler();
            var mockRequest = mockHttp.When(HttpMethod.Post, config.Uri)
                              .WithFormData("client_id", config.ClientId)
                              .WithFormData("client_secret", config.ClientSecret)
                              .Respond(HttpStatusCode.OK, "application/json",
                                       JsonConvert.SerializeObject(new OidcAuthenticationToken
            {
                AccessToken = "6015CF7142BA060F5026BE9CC442C12ED7F0D5AECCBAA0678DEEBC51C6A1B282",
                ExpiresIn   = expiryTimeInSeconds
            }));

            var httpClient = mockHttp.ToHttpClient();

            await handler.GetToken(httpClient);

            await Task.Delay(TimeSpan.FromSeconds(1));

            await handler.GetToken(httpClient);

            Assert.Equal(expectedStsCallCount, mockHttp.GetMatchCount(mockRequest));
        }
Example #4
0
        public async Task AuthorisationTokenSuccessTests(string expectedAccessToken)
        {
            var expectedResponse = JsonConvert.SerializeObject(new OidcAuthenticationToken
            {
                AccessToken = expectedAccessToken
            });

            var config = new OidcAuthenticationConfig
            {
                ClientId     = "bob",
                ClientSecret = "bobsecret",
                Uri          = "https://localhost/authendpoint"
            };

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.When(HttpMethod.Post, config.Uri)
            .WithHeaders("client_id", config.ClientId)
            .WithHeaders("client_secret", config.ClientSecret)
            .WithContentType("application/json-patch+json; charset=utf-8", string.Empty)
            .Respond(HttpStatusCode.Created, "application/json-patch+json", expectedResponse);

            var httpClientFactory = new HttpClientFactory(new Dictionary <string, HttpClient> {
                { new Uri(config.Uri).Host, mockHttp.ToHttpClient() }
            });


            var handler    = new MmAuthenticationHandler(httpClientFactory, config, _bigBrother);
            var httpClient = mockHttp.ToHttpClient();
            var token      = await handler.GetTokenAsync(_cancellationToken);

            Assert.NotNull(token);
            Assert.NotEmpty(token);
            Assert.StartsWith("Bearer ", token);
        }
        public async Task AuthorisationTokenSuccessTests(string expectedAccessToken)
        {
            var expectedResponse = JsonConvert.SerializeObject(new OidcAuthenticationToken
            {
                AccessToken = expectedAccessToken
            });

            var config = new OidcAuthenticationConfig
            {
                ClientId     = "bob",
                ClientSecret = "bobsecret",
                Uri          = "http://localhost/authendpoint"
            };

            var mockHttp = new MockHttpMessageHandler();

            mockHttp.When(HttpMethod.Post, config.Uri)
            .WithHeaders("client_id", config.ClientId)
            .WithHeaders("client_secret", config.ClientSecret)
            .WithContentType("application/json-patch+json", string.Empty)
            .Respond(HttpStatusCode.Created, "application/json-patch+json", expectedResponse);

            var handler    = new MmAuthenticationHandler(config);
            var httpClient = mockHttp.ToHttpClient();
            await handler.GetToken(httpClient);

            Assert.NotNull(httpClient.DefaultRequestHeaders.Authorization);
            Assert.Equal(expectedAccessToken, httpClient.DefaultRequestHeaders.Authorization.Parameter);
            Assert.Equal("Bearer", httpClient.DefaultRequestHeaders.Authorization.Scheme);
        }
        public OidcAuthenticationHandler(IHttpClientFactory httpClientFactory, AuthenticationConfig authenticationConfig, IBigBrother bigBrother)
        {
            var oAuthAuthenticationToken = authenticationConfig as OidcAuthenticationConfig;

            OidcAuthenticationConfig = oAuthAuthenticationToken ?? throw new ArgumentException($"configuration for basic authentication is not of type {typeof(OidcAuthenticationConfig)}", nameof(authenticationConfig));
            HttpClientFactory        = httpClientFactory;
            BigBrother = bigBrother;
        }
        protected static void ReportTokenUpdateFailure(OidcAuthenticationConfig config, TokenResponse response)
        {
            if (!response.IsError)
            {
                return;
            }

            throw new ClientTokenFailureException(response.Exception)
                  {
                      ClientId         = config.ClientId,
                      Scopes           = string.Join(" ", config.Scopes),
                      TokenType        = response.TokenType,
                      Uri              = config.Uri,
                      Error            = response.Error,
                      ErrorCode        = response.HttpStatusCode,
                      ErrorDescription = response.ErrorDescription,
                      HttpErrorReason  = response.HttpErrorReason,
                      ResponsePayload  = response.Json.ToString(Formatting.None)
                  };
        }
        public async Task RefreshToken(int refreshBeforeInSeconds, int expiryTimeInSeconds, int expectedStsCallCount, string expectedToken)
        {
            var config = new OidcAuthenticationConfig
            {
                ClientId               = "bob",
                ClientSecret           = "bobsecret",
                Scopes                 = new[] { "bob.scope.all" },
                Uri                    = "http://localhost/authendpoint",
                RefreshBeforeInSeconds = refreshBeforeInSeconds
            };

            var mockHttp    = new MockHttpMessageHandler();
            var mockRequest = mockHttp.When(HttpMethod.Post, config.Uri)
                              .WithFormData("client_id", config.ClientId)
                              .WithFormData("client_secret", config.ClientSecret)
                              .Respond(HttpStatusCode.OK, "application/json",
                                       JsonConvert.SerializeObject(new OidcAuthenticationToken
            {
                AccessToken = expectedToken,
                ExpiresIn   = expiryTimeInSeconds
            }));

            var handler = new OidcAuthenticationHandler(
                new HttpClientFactory(
                    new Dictionary <string, HttpClient>
            {
                { new Uri(config.Uri).Host, mockHttp.ToHttpClient() },
            }),
                config,
                _bigBrother);

            await handler.GetTokenAsync(_cancellationToken);

            await Task.Delay(TimeSpan.FromSeconds(1), _cancellationToken);

            var token = await handler.GetTokenAsync(_cancellationToken);

            Assert.Equal(expectedStsCallCount, mockHttp.GetMatchCount(mockRequest));
            Assert.Equal($"Bearer {expectedToken}", token);
        }
Example #9
0
        public OidcAuthenticationHandler(AuthenticationConfig authenticationConfig)
        {
            var oAuthAuthenticationToken = authenticationConfig as OidcAuthenticationConfig;

            OidcAuthenticationConfig = oAuthAuthenticationToken ?? throw new ArgumentException($"configuration for basic authentication is not of type {typeof(OidcAuthenticationConfig)}", nameof(authenticationConfig));
        }