Exemple #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="eventEndpoint"></param>
        public AuditTrailClient(string eventEndpoint, string scope, TokenClientOptions tokenClientOptions)
        {
            if (eventEndpoint is null)
            {
                throw new ArgumentNullException(nameof(eventEndpoint));
            }

            if (scope is null)
            {
                throw new ArgumentNullException(nameof(scope));
            }

            if (tokenClientOptions is null)
            {
                throw new ArgumentNullException(nameof(tokenClientOptions));
            }

            _httpClient = new HttpClient();
            _sink       = new NullSink();
            _logger     = new ConsoleLogger <AuditTrailClient>();
            _writer     = new JwtWriter();
            _store      = new NullStore();
            _options    = new AuditTrailClientOptions
            {
                DeliveryEndpoint   = eventEndpoint,
                AccessTokenScope   = scope,
                TokenClientOptions = tokenClientOptions
            };
            _accessTokenAcquirer = new DefaultAccessTokenAcquirer(
                new ConsoleLogger <DefaultAccessTokenAcquirer>(),
                new TokenClient(new HttpClient(), tokenClientOptions),
                Options.Create(_options));
        }
 /// <summary>
 /// Constructs a JwtAssertionTokenClient with specified options
 /// </summary>
 /// <param name="options">Token client options</param>
 public JwtAssertionTokenClient(TokenClientOptions options)
 {
     ValidateOptions(options);
     _cache = options.Cache ?? DefaultTokenCache.Value;
     _internalClient = new PrivateKeyJwtClientCredentialsTokenClient(options);
     _partialCacheKey = string.Join("|", options.TokenEndpointUrl, options.ClientId, options.Certificate.Thumbprint);
 }
 public JwtAssertionFactory(TokenClientOptions options)
 {
     _audience = options.Audience ?? options.TokenEndpointUrl;
     _clientId = options.ClientId;
     _certificate = options.Certificate;
     _embedCertificate = options.EmbedCertificate;
 }
        public async Task <string> GetRefreshAccessToken()
        {
            var discoClient = await client.GetDiscoveryDocumentAsync(Configuration["AuthServer:AuthBaseUrl"]);

            var tokenClientOptions = new TokenClientOptions
            {
                Address = Configuration["AuthServer:AuthBaseUrl"],
                AuthorizationHeaderStyle = BasicAuthenticationHeaderStyle.Rfc6749,
                ClientId     = Configuration["AuthServer:ClientId"],
                ClientSecret = Configuration["AuthServer:ClientSecret"]
            };

            var tokenClient = new TokenClient(client, tokenClientOptions);


            var refreshToken = await _httpContextAccessor.HttpContext.GetTokenAsync(OpenIdConnectParameterNames.RefreshToken);

            var tokenResponse = await tokenClient.RequestRefreshTokenAsync(refreshToken);

            if (!tokenResponse.IsError)
            {
                var auth = await _httpContextAccessor.HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

                auth.Properties.UpdateTokenValue(OpenIdConnectParameterNames.AccessToken, tokenResponse.AccessToken);
                auth.Properties.UpdateTokenValue(OpenIdConnectParameterNames.RefreshToken, tokenResponse.RefreshToken);

                var expieresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResponse.ExpiresIn);
                auth.Properties.UpdateTokenValue("expieres_at", expieresAt.ToString("o", CultureInfo.InvariantCulture));
                await _httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, auth.Principal, auth.Properties);

                return(tokenResponse.AccessToken);
            }
            //return await GetAccessToken();
            throw tokenResponse.Exception;
        }
Exemple #5
0
        public string Login()//string Login, string Password)
        {
            var ru      = new RequestUrl("https://localhost:6001/connect/authorize");
            var payload = new
            {
                token = "mmm"
            };
            TokenClientOptions tco = new TokenClientOptions();
            // create token client
            //var client = new TokenClient(tco);

            // send custom grant to token endpoint, return response
            //return await client.RequestCustomGrantAsync("delegation", "api2", payload);
            var client = new HttpClient();
            var s      = new TokenJson
            {
                Token = "123"
            };
            var         d   = System.Text.Json.Serialization.JsonSerializer.ToString(s);
            HttpContent con = new StringContent(d);

            con.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

            var dupa = new Dictionary <string, string>();

            dupa.Add("Token", "123");
            var response = client.RequestTokenAsync(new TokenRequest
            {
                Address = "https://localhost:6001/connect/token",

                ClientId     = "userid",
                ClientSecret = "apisecret",
                GrantType    = "userid",
                Parameters   = dupa
            }).Result;


            //var response = client.RequestPasswordTokenAsync(new PasswordTokenRequest
            //{
            //    Address = "https://localhost:6001/connect/token",

            //    ClientId = "ApiClient",
            //    ClientSecret = "apisecret",
            //    Scope = "profile",

            //    UserName = "******",
            //    Password = "******"
            //}).Result;

            if (response.IsError)
            {
            }

            return(response.AccessToken);
        }
        public RealAuthorizationServerTest()
        {
            var options = new TokenClientOptions()
            {
                TokenEndpointUrl = "https://localhost:44300/connect/token",
                ClientId = "test_client",
                Certificate = TestCertificate.Load()
            };

            _tokenClient = new JwtAssertionTokenClient(options);
        }
Exemple #7
0
        public void CreateClient_TokenClientOptionsPropertiesMayBeNull_ThrowsArgumentException()
        {
            var tokenClientOptions = new TokenClientOptions();

            var exception = Assert.Throws <ArgumentException>(() => _tokenManagerFixture.GetTokenClientFactory().CreateClient(tokenClientOptions));

            Assert.Equal("'AuthorityUrl' must not be null, empty or whitespace. (Parameter 'AuthorityUrl')", exception.Message);

            tokenClientOptions.AuthorityUrl = "localhost";
            exception = Assert.Throws <ArgumentException>(() => _tokenManagerFixture.GetTokenClientFactory().CreateClient(tokenClientOptions));
            Assert.Equal("'ClientId' must not be null, empty or whitespace. (Parameter 'ClientId')", exception.Message);
        }
Exemple #8
0
    // ReSharper disable once InconsistentNaming
    private async Task <string> ObtainSTSAccessToken()
    {
        var httpClient = new HttpClient();
        var discovery  = await httpClient.GetDiscoveryDocumentAsync(TestConfig.STSAuthority);

        var options = new TokenClientOptions
        {
            Address      = discovery.TokenEndpoint,
            ClientId     = TestConfig.STSClientId,
            ClientSecret = TestConfig.STSClientSecret,
        };
        var client        = new TokenClient(httpClient, options);
        var tokenResponse = await client.RequestClientCredentialsTokenAsync(TestConfig.STSScope);

        return(tokenResponse.AccessToken);
    }
        public static async Task Main(string[] args)
        {
            var httpClient = new HttpClient();
            var options    = new TokenClientOptions
            {
                Address      = "http://localhost:5000/connect/token",
                ClientId     = "ro.client",
                ClientSecret = "secret"
            };
            var tokenClient   = new TokenClient(httpClient, options);
            var tokenResponse = await tokenClient.RequestClientCredentialsTokenAsync("api1");

            Console.WriteLine("Error : {0}", tokenResponse.Error);
            Console.WriteLine("Token : {0}", tokenResponse.AccessToken);
            Console.Read();
        }
Exemple #10
0
        static void Main(string[] args)
        {
            var options = new TokenClientOptions();

            options.AudienceUri              = new Uri("http://localhost");
            options.StoreName                = StoreName.Root;
            options.StoreLocation            = StoreLocation.LocalMachine;
            options.CertificateDnsIdentity   = "SecureTokenServiceTest";
            options.SubjectDistinguishedName = "CN=SecureTokenServiceTest";
            options.TokenServiceUri          = new Uri("http://localhost:6690/STS");


            var unityContainer = new UnityContainer();

            unityContainer.RegisterType <TrustedIssuerNameRegistry>();
            unityContainer.RegisterInstance(typeof(ITokenClientOptions), options);
            unityContainer.RegisterType <TokenClient>();

            Console.WriteLine("Login test");

            try
            {
                Console.WriteLine("Valid test");
                var client = unityContainer.Resolve <TokenClient>();
                client.SignIn("Dessel Bane", "pass");

                foreach (Claim claimsPrincipalClaim in client.SessionToken.ClaimsPrincipal.Claims)
                {
                    Console.WriteLine($"Claim type: {claimsPrincipalClaim.Type}, Claim Value: {claimsPrincipalClaim.Value}");
                }

                client.SignOut();

                client.SignIn("Dessel Bane", "pas123s");

                Console.WriteLine(client?.SessionToken?.ClaimsPrincipal?.Identity?.Name ?? "Not Authenticated");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        /// <inheritdoc />
        public ITokenClient CreateClient([NotNull] TokenClientOptions tokenClientOptions)
        {
            if (tokenClientOptions == null)
            {
                throw new ArgumentNullException(nameof(tokenClientOptions));
            }
            if (string.IsNullOrWhiteSpace(tokenClientOptions.AuthorityUrl))
            {
                throw new ArgumentException($"'{nameof(tokenClientOptions.AuthorityUrl)}' must not be null, empty or whitespace.", nameof(tokenClientOptions.AuthorityUrl));
            }
            if (string.IsNullOrWhiteSpace(tokenClientOptions.ClientId))
            {
                throw new ArgumentException($"'{nameof(tokenClientOptions.ClientId)}' must not be null, empty or whitespace.", nameof(tokenClientOptions.ClientId));
            }

            return(new TokenClient(_httpClientFactory.CreateClient(),
                                   _loggerFactory.CreateLogger <TokenClient>(),
                                   tokenClientOptions, _dateTimeProvider));
        }
        /// <inheritdoc/>
        public async Task <TokenResponse> RequestClientAccessToken(string clientName = AccessTokenManagementDefaults.DefaultTokenClientName)
        {
            TokenClientOptions tokenClientOptions;

            // if a named client configuration was passed in, try to load it
            if (string.Equals(clientName, AccessTokenManagementDefaults.DefaultTokenClientName))
            {
                // if only one client configuration exists, load that
                if (_accessTokenManagementOptions.Client.Clients.Count == 1)
                {
                    tokenClientOptions = _accessTokenManagementOptions.Client.Clients.First().Value;
                }
                // otherwise fall back to the scheme configuration
                else
                {
                    var(options, configuration) = await GetOpenIdConnectSettingsAsync(_accessTokenManagementOptions.User.Scheme);

                    tokenClientOptions = new TokenClientOptions
                    {
                        Address = configuration.TokenEndpoint,

                        ClientId     = options.ClientId,
                        ClientSecret = options.ClientSecret
                    };
                }
            }
            else
            {
                if (!_accessTokenManagementOptions.Client.Clients.TryGetValue(clientName, out tokenClientOptions))
                {
                    throw new InvalidOperationException($"No access token client configuration found for client: {clientName}");
                }
            }

            return(await _httpClient.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = tokenClientOptions.Address,

                ClientId = tokenClientOptions.ClientId,
                ClientSecret = tokenClientOptions.ClientSecret
            }));
        }
Exemple #13
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Set the client details and the idsvc token endpoint address
            TokenClientOptions tokenOptions = new TokenClientOptions
            {
                ClientId     = "rshp.gateway",
                ClientSecret = "secret", // DEV: for development purposes. Use proper secret in prod.
                Address      = "http://identity.svc/connect/token"
            };

            var client = new TokenClient(new HttpClient(), tokenOptions);

            // Get currently attached token (reference) from downstream-bound request
            var accessToken = request.Headers.Authorization.Parameter;

            _logger.LogDebug("Exchanging reference token to JWT - reference token: {0} ", accessToken);

            // Set desired scope and attach current reference token
            var opt = new Dictionary <string, string>
            {
                { "scope", "bm acc" },
                { "reference_token", accessToken }
            };

            // Send request for token using custom grant type
            var tokenResponse = await client.RequestTokenAsync("exchange_reference_token", opt);

            _logger.LogDebug("Token exchange result: {0}", tokenResponse?.AccessToken);

            // Modify request with new JWT token if it returned successfully
            if (!tokenResponse.IsError)
            {
                request.SetBearerToken(tokenResponse.AccessToken);
            }
            else
            {
                _logger.LogError("RequestTokenAsync() Failed! {0}, {1} \t Exception: {2}", tokenResponse.Error, tokenResponse.ErrorDescription, tokenResponse.Exception.ToString());
            }

            _logger.LogDebug("Final token result: {0}", request.Headers.Authorization.Parameter);
            return(await base.SendAsync(request, cancellationToken));
        }
        public async Task Local_custom_parameters_should_not_interfere_with_global()
        {
            var globalOptions = new TokenClientOptions {
                Parameters = { { "global", "value" } }
            };
            var tokenClient = new TokenClient(_client, globalOptions);

            var localParameters = new Dictionary <string, string>
            {
                { "client_id", "custom" },
                { "client_secret", "custom" },
                { "custom", "custom" }
            };

            _ = await tokenClient.RequestTokenAsync(grantType : "test", parameters : localParameters);

            globalOptions.Parameters.Should().HaveCount(1);
            globalOptions.Parameters.TryGetValue("global", out var globalValue);
            globalValue.Should().Be("value");
        }
Exemple #15
0
        public async Task Local_custom_parameters_should_not_interfere_with_global()
        {
            var globalOptions = new TokenClientOptions {
                Parameters = { { "global", "value" } }
            };
            var tokenClient = new TokenClient(_client, globalOptions);

            var localParameters = new Parameters
            {
                { "client_id", "custom" },
                { "client_secret", "custom" },
                { "custom", "custom" }
            };

            _ = await tokenClient.RequestTokenAsync(grantType : "test", parameters : localParameters);

            globalOptions.Parameters.Should().HaveCount(1);
            var globalValue = globalOptions.Parameters.FirstOrDefault(p => p.Key == "global").Value;

            globalValue.Should().Be("value");
        }
Exemple #16
0
        /// <summary>
        /// Get access token.
        /// </summary>
        /// <param name="baseUrl">the base url</param>
        /// <param name="userName">the username</param>
        /// <param name="password">the password</param>
        public static async Task <string> GetAccessToken(string baseUrl, string userName, string password)
        {
            //TODO replace all hardcoded strings
            var tokenOptions = new TokenClientOptions
            {
                Address      = baseUrl + TokenEndPoint,
                ClientId     = "chat_console_client",
                ClientSecret = "superdupersecret"
            };
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (message, xCertificate2, chain, errors) => true
            };
            // Get a token.
            var tokenClient   = new TokenClient(new HttpMessageInvoker(handler), tokenOptions);
            var tokenResponse = await tokenClient.RequestPasswordTokenAsync(userName, password, "shortlivedchat");

            if (!tokenResponse.IsError)
            {
                return(tokenResponse.AccessToken);
            }
            Console.WriteLine(tokenResponse.Error);
            return(null);
        }
        private void ValidateOptions(TokenClientOptions options)
        {
            if (options == null)
            {
                throw new ArgumentException("Options cannot be null", nameof(options));
            }

            if (string.IsNullOrWhiteSpace(options.TokenEndpointUrl))
            {
                throw new ArgumentException("TokenEndpointUrl must be set", nameof(options.TokenEndpointUrl));
            }

            if (string.IsNullOrWhiteSpace(options.ClientId))
            {
                throw new ArgumentException("ClientId must be set", nameof(options.ClientId));
            }

            if (options.Certificate == null)
            {
                throw new ArgumentException("Certificate must be set", nameof(options.Certificate));
            }

            ValidateCertificate(options.Certificate);
        }
Exemple #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TokenClient"/> class.
 /// </summary>
 /// <param name="client">The client func.</param>
 /// <param name="options">The options.</param>
 /// <exception cref="ArgumentNullException">client</exception>
 public TokenClient(Func <HttpMessageInvoker> client, TokenClientOptions options)
 {
     _client  = client ?? throw new ArgumentNullException(nameof(client));
     _options = options ?? throw new ArgumentNullException(nameof(options));
 }
Exemple #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TokenClient"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="options">The options.</param>
 /// <exception cref="ArgumentNullException">client</exception>
 public TokenClient(HttpMessageInvoker client, TokenClientOptions options)
     : this(() => client, options)
 {
 }
 public PrivateKeyJwtClientCredentialsTokenClient(TokenClientOptions options)
 {
     _jwtAssertionFactory = new JwtAssertionFactory(options);
     _tokenEndpointUrl = options.TokenEndpointUrl;
     _clientId = options.ClientId;
 }
Exemple #21
0
        /// <summary>
        /// Refreshes the Api tokens for the given ApplicationUser
        /// </summary>
        /// <param name="user"></param>
        /// <param name="signInUser"></param>
        /// <returns></returns>
        public async Task <bool> RefreshTokens(ApplicationUser user, bool signInUser = false)
        {
            var lichessAuthNSection = _configuration.GetSection("Authentication:Lichess");

            HttpMessageHandler _handler = new HttpClientHandler();
            HttpClient         _client  = new HttpClient(_handler)
            {
                BaseAddress = new Uri(AspNet.Security.OAuth.Lichess.LichessAuthenticationDefaults.TokenEndpoint)
            };

            TokenClientOptions options = new TokenClientOptions
            {
                ClientId     = lichessAuthNSection["ClientID"],
                ClientSecret = lichessAuthNSection["ClientSecret"]
            };

            var tokenClient = new TokenClient(_client, options);
            var rt          = user.RefreshToken;
            var tokenResult = await tokenClient.RequestRefreshTokenAsync(rt);

            if (!tokenResult.IsError)
            {
                var newAccessToken  = tokenResult.AccessToken;
                var newRefreshToken = tokenResult.RefreshToken;
                var expiresAt       = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResult.ExpiresIn);

                if (signInUser)
                {
                    var tokens = new List <AuthenticationToken>
                    {
                        new AuthenticationToken
                        {
                            Name = OpenIdConnectParameterNames.AccessToken, Value = newAccessToken
                        },
                        new AuthenticationToken
                        {
                            Name = OpenIdConnectParameterNames.RefreshToken, Value = newRefreshToken
                        },
                        new AuthenticationToken
                        {
                            Name = "expires_at", Value = expiresAt.ToString("o", CultureInfo.InvariantCulture)
                        }
                    };

                    var props = new AuthenticationProperties();
                    props.StoreTokens(tokens);
                    props.IsPersistent = true;

                    await _signInManager.SignInAsync(user, props);
                }

                user.AccessToken  = newAccessToken;
                user.RefreshToken = newRefreshToken;
                user.ExpiresAt    = expiresAt;

                await _userManager.UpdateAsync(user);

                return(true);
            }

            return(false);
        }
 public void Configure(ExternalExchangeRecord externalExchangeRecord)
 {
     _externalExchangeRecord = externalExchangeRecord;
     _settings = _optionsSnapshot.Get(_externalExchangeRecord.ExchangeName);
     _cacheKey = $"{_externalExchangeRecord.ExchangeName}_{_cacheKey}";
 }
 public TokenClient(TokenClientOptions options)
 {
     _log        = Log.ForContext <TokenClient>();
     BaseAddress = new Uri(options.TokenUrl);
 }