public async Task Valid_Client()
        {
            var client = new TokenClient(
                TokenEndpoint,
                "client.custom",
                "secret",
                innerHttpMessageHandler: _handler);

            var customParameters = new Dictionary<string, string>
                {
                    { "custom_credential", "custom credential"}
                };

            var response = await client.RequestCustomGrantAsync("custom", "api1", customParameters);

            response.IsError.Should().Be(false);
            response.ExpiresIn.Should().Be(3600);
            response.TokenType.Should().Be("Bearer");
            response.IdentityToken.Should().BeNull();
            response.RefreshToken.Should().BeNull();

            var payload = GetPayload(response);

            payload.Count().Should().Be(10);
            payload.Should().Contain("iss", "https://idsrv4");
            payload.Should().Contain("aud", "https://idsrv4/resources");
            payload.Should().Contain("client_id", "client.custom");
            payload.Should().Contain("scope", "api1");
            payload.Should().Contain("sub", "818727");
            payload.Should().Contain("idp", "idsrv");

            var amr = payload["amr"] as JArray;
            amr.Count().Should().Be(1);
            amr.First().ToString().Should().Be("custom");
        }
        public async Task<IHttpActionResult> RefreshToken(RefreshTokenRequest refreshTokenRequest)
        {
            var tokenClient = new TokenClient("https://localhost:44302/connect/token", "AngularClient", "secret");

            var result = await tokenClient.RequestRefreshTokenAsync(refreshTokenRequest.RefreshAccessToken);

            return Ok(new
            {
                result.AccessToken,
                result.RefreshToken
            });
        }
        public async Task Valid_User_IdentityScopes()
        {
            var client = new TokenClient(
                TokenEndpoint,
                "roclient",
                "secret",
                innerHttpMessageHandler: _handler);

            var response = await client.RequestResourceOwnerPasswordAsync("bob", "bob", "openid email api1");

            response.IsError.Should().Be(false);
            response.ExpiresIn.Should().Be(3600);
            response.TokenType.Should().Be("Bearer");
            response.IdentityToken.Should().BeNull();
            response.RefreshToken.Should().BeNull();

            var payload = GetPayload(response);

            payload.Count().Should().Be(10);
            payload.Should().Contain("iss", "https://idsrv3");
            payload.Should().Contain("aud", "https://idsrv3/resources");
            payload.Should().Contain("client_id", "roclient");
            payload.Should().Contain("sub", "88421113");
            payload.Should().Contain("idp", "idsrv");

            var amr = payload["amr"] as JArray;
            amr.Count().Should().Be(1);
            amr.First().ToString().Should().Be("password");

            var scopes = payload["scope"] as JArray;
            scopes.Count().Should().Be(3);
            scopes.First().ToString().Should().Be("api1");
            scopes.Skip(1).First().ToString().Should().Be("email");
            scopes.Skip(2).First().ToString().Should().Be("openid");
        }
        public async Task<ActionResult> GetToken()
        {
            var client = new TokenClient(
                Constants.TokenEndpoint,
                "codeclient",
                "secret");

            var code = Request.QueryString["code"];
            var tempState = await GetTempStateAsync();
            Request.GetOwinContext().Authentication.SignOut("TempState");

            var response = await client.RequestAuthorizationCodeAsync(
                code,
                "https://localhost:44312/callback");

            await ValidateResponseAndSignInAsync(response, tempState.Item2);

            if (!string.IsNullOrEmpty(response.IdentityToken))
            {
                ViewBag.IdentityTokenParsed = ParseJwt(response.IdentityToken);
            }
            if (!string.IsNullOrEmpty(response.AccessToken))
            {
                ViewBag.AccessTokenParsed = ParseJwt(response.AccessToken);
            }

            return View("Token", response);
        }
        public async Task Token_endpoint_supports_client_authentication_with_basic_authentication_with_POST()
        {
            await _pipeline.LoginAsync("bob");

            var nonce = Guid.NewGuid().ToString();

            _pipeline.BrowserClient.AllowAutoRedirect = false;
            var url = _pipeline.CreateAuthorizeUrl(
                           clientId: "code_pipeline.Client",
                           responseType: "code",
                           scope: "openid",
                           redirectUri: "https://code_pipeline.Client/callback?foo=bar&baz=quux",
                           nonce: nonce);
            var response = await _pipeline.BrowserClient.GetAsync(url);

            var authorization = _pipeline.ParseAuthorizationResponseUrl(response.Headers.Location.ToString());
            authorization.Code.Should().NotBeNull();

            var code = authorization.Code;

            // backchannel client
            var wrapper = new MessageHandlerWrapper(_pipeline.Handler);
            var tokenClient = new TokenClient(MockAuthorizationPipeline.TokenEndpoint, "code_pipeline.Client", "secret", wrapper);
            var tokenResult = await tokenClient.RequestAuthorizationCodeAsync(code, "https://code_pipeline.Client/callback?foo=bar&baz=quux");

            tokenResult.IsError.Should().BeFalse();
            tokenResult.IsHttpError.Should().BeFalse();
            tokenResult.TokenType.Should().Be("Bearer");
            tokenResult.AccessToken.Should().NotBeNull();
            tokenResult.ExpiresIn.Should().BeGreaterThan(0);
            tokenResult.IdentityToken.Should().NotBeNull();

            wrapper.Response.Headers.CacheControl.NoCache.Should().BeTrue();
            wrapper.Response.Headers.CacheControl.NoStore.Should().BeTrue();
        }
        public async Task Valid_Client_Multiple_Scopes()
        {
            var client = new TokenClient(
                TokenEndpoint,
                "client",
                "secret",
                innerHttpMessageHandler: _handler);

            var response = await client.RequestClientCredentialsAsync("api1 api2");

            response.IsError.Should().Be(false);
            response.ExpiresIn.Should().Be(3600);
            response.TokenType.Should().Be("Bearer");
            response.IdentityToken.Should().BeNull();
            response.RefreshToken.Should().BeNull();

            var payload = GetPayload(response);

            payload.Count().Should().Be(6);
            payload.Should().Contain("iss", "https://idsrv4");
            payload.Should().Contain("aud", "https://idsrv4/resources");
            payload.Should().Contain("client_id", "client");

            var scopes = payload["scope"] as JArray;
            scopes.Count().Should().Be(2);
            scopes.First().ToString().Should().Be("api1");
            scopes.Skip(1).First().ToString().Should().Be("api2");
        }
		static void Main(string[] args)
		{
			var tokenClient = new TokenClient(
				"http://localhost:18942/connect/token",
				"test",
				"secret");

			//This responds with the token for the "api" scope, based on the username/password above
			var response = tokenClient.RequestClientCredentialsAsync("api1").Result;

			//Test area to show api/values is protected
			//Should return that the request is unauthorized
			try
			{
				var unTokenedClient = new HttpClient();
				var unTokenedClientResponse = unTokenedClient.GetAsync("http://localhost:19806/api/values").Result;
				Console.WriteLine("Un-tokened response: {0}", unTokenedClientResponse.StatusCode);
			}
			catch (Exception ex)
			{
				Console.WriteLine("Exception of: {0} while calling api without token.", ex.Message);
			}


			//Now we make the same request with the token received by the auth service.
			var client = new HttpClient();
			client.SetBearerToken(response.AccessToken);

			var apiResponse = client.GetAsync("http://localhost:19806/identity").Result;
			var callApiResponse = client.GetAsync("http://localhost:19806/api/values").Result;
			Console.WriteLine("Tokened response: {0}", callApiResponse.StatusCode);
			Console.WriteLine(callApiResponse.Content.ReadAsStringAsync().Result);
			Console.Read();
		}
        private static string RequestAccessTokenClientCredentials()
        {
            //did we  store the token before?

            var cookie = HttpContext.Current.Request.Cookies.Get("tripGalleryCookie");


            if (cookie != null && cookie["access_token"] != null)
            {
                return cookie["access_token"];
            }


            var tokenClient = new TokenClient(
                    TripGallery.Constants.TripGallerySTSTokenEndpoint,
                    "tripgalleryclientcredentials",
                    TripGallery.Constants.TripGalleryClientSecret
                );


            var tokenResponse = tokenClient.RequestClientCredentialsAsync("gallerymanagement").Result;

            //just to debug
            TokenHelper.DecodeAndWrite(tokenResponse.AccessToken);

            //save token in a cookie 
            HttpContext.Current.Response.Cookies["TripGalleryCookie"]["access_token"] = tokenResponse.AccessToken;



            return tokenResponse.AccessToken;

        }
        /// <summary>
        /// request ID server for a token using the ClientId and secret
        /// </summary>
        /// <returns>An access token in string format</returns>
        private static string RequestAccessTokenClientCredentials(string clientId,string secret)
        {
            // did we store the token before?
            var cookie = HttpContext.Current.Request.Cookies.Get("TripGalleryCookie");
            if (cookie != null && cookie["access_token"] != null)
            {
                return cookie["access_token"];
            }

            // no token found - get one

            // create an oAuth2 Client
            var oAuth2Client = new TokenClient(
                      TripGallery.Constants.TripGallerySTSTokenEndpoint,
                      clientId,
                      secret);

            // ask for a token, containing the gallerymanagement scope
            var tokenResponse = oAuth2Client.RequestClientCredentialsAsync("gallerymanagement").Result;

            // decode & write out the token, so we can see what's in it
               // TokenHelper.DecodeAndWrite(tokenResponse.AccessToken);

            // we save the token in a cookie for use later on
            HttpContext.Current.Response.Cookies["TripGalleryCookie"]["access_token"] = tokenResponse.AccessToken;

            // return the token
            return tokenResponse.AccessToken;
        }
Esempio n. 10
0
 /// <summary>
 /// Busca o token de acesso no IdentityServer para ser utilizado na API.
 /// </summary>
 /// <returns></returns>
 private async Task<TokenResponse> GetTokenAsync()
 {
     var client = new TokenClient("https://localhost:44302/identity/connect/token"
         , "mvc_service"
         , "secret");
     return await client.RequestClientCredentialsAsync("gac_erp_appservice");
 }
Esempio n. 11
0
        static void Main(string[] args)
        {
            _tokenClient = new TokenClient(
                Constants.TokenEndpoint,
                "roclient",
                "secret");

            var response = RequestToken();
            ShowResponse(response);

            Console.ReadLine();

            var refresh_token = response.RefreshToken;

            while (true)
            {
                response = RefreshToken(refresh_token);
                ShowResponse(response);

                Console.ReadLine();
                CallService(response.AccessToken);

                if (response.RefreshToken != refresh_token)
                {
                    refresh_token = response.RefreshToken;
                }
            }
        }
Esempio n. 12
0
        public static TokenResponse GetClientToken()
        {
            var client = new TokenClient("https://localhost:44333/connect/token", "carbon",
                "21B5F798-BE55-42BC-8AA8-0025B903DC3B");

            //return client.RequestClientCredentialsAsync("LeagueComparer").Result;
            return client.RequestResourceOwnerPasswordAsync("bob", "secret", "LeagueComparer").Result;
        }
 static TokenResponse GetClientToken()
 {
     var client = new TokenClient(
         "https://100.105.80.38:13855/connect/token",
         "silicon",
         "F621F470-9731-4A25-80EF-67A6F7C5F4B8");
     return client.RequestClientCredentialsAsync("api1").Result;
 }
        private async static Task<string> RequestToken()
        {
            var tokenClient = new TokenClient("https://localhost:44302/connect/token", "ConsoleClient", "secret");

            var response = await tokenClient.RequestClientCredentialsAsync("Api");

            return response.AccessToken;
        }
Esempio n. 15
0
        static TokenResponse GetClientToken()
        {
            var client = new TokenClient("https://localhost:44333/connect/token",
                                          "freightshare1",
                                          "IIPiBTywUcK5Qv0kvmVXbSiax5wBStDMGTAIA0T/RSM=");

            return client.RequestClientCredentialsAsync("api1").Result;
        }
Esempio n. 16
0
 static TokenResponse GetToken(string tokenUrl, string clientId, string secret, string scope, string username = null, string password = null)
 {
     var client = new TokenClient(tokenUrl, clientId, secret);
    if (string.IsNullOrWhiteSpace(username)||string.IsNullOrWhiteSpace(password))
         return client.RequestClientCredentialsAsync(scope).Result;
     else
         return client.RequestResourceOwnerPasswordAsync(username, password, scope).Result;
 }
        private async Task<TokenResponse> GetTokenAsync()
        {
            var client = new TokenClient(IdConstants.IdHost +
                "identity/connect/token",
                "mvc_service",
                "secret");

            return await client.RequestClientCredentialsAsync("sampleApi");
        }
Esempio n. 18
0
        /// <summary>
        /// Request an access token on behalf of a user
        /// </summary>
        static TokenResponse GetUserToken()
        {
            var client = new TokenClient("https://localhost:44333/connect/token",
                                          "freightshare2",
                                          "IIPiBTywUcK5Qv0kvmVXbSiax5wBStDMGTAIA0T/RSM=");

            //return client.RequestResourceOwnerPasswordAsync("bob", "secret", "api1").Result;
            return client.RequestResourceOwnerPasswordAsync("alice", "secret", "api1").Result;
        }
Esempio n. 19
0
        static TokenResponse GetUserToken()
        {
            var client = new TokenClient(
                "https://localhost:44333/connect/token",
                "carbon",
                "21B5F798-BE55-42BC-8AA8-0025B903DC3B");

            return client.RequestResourceOwnerPasswordAsync("bob", "secret", "api1").Result;
        }
Esempio n. 20
0
        static TokenResponse RequestToken()
        {
            var client = new TokenClient(
                Constants.TokenEndpoint,
                "ro.client",
                "secret");

            return client.RequestResourceOwnerPasswordAsync("bob", "bob", "openid email").Result;
        }
Esempio n. 21
0
        //requests the access token using the client credentials
        static TokenResponse GetClientToken()
        {
            var client = new TokenClient(
                "http://localhost:44333/connect/token",
                "silicon",
                "F621F470-9731-4A25-80EF-67A6F7C5F4B8");

            return client.RequestClientCredentialsAsync("api1").Result;
        }
Esempio n. 22
0
        static TokenResponse RequestToken()
        {
            var client = new TokenClient(
                Constants.TokenEndpoint,
                "client",
                "secret");

            return client.RequestClientCredentialsAsync("read write").Result;
        }
Esempio n. 23
0
        static TokenResponse GetToken()
        {
            var client = new TokenClient(
                "http://localhost:44333/connect/token",
                "ConsoleApplication",
                "F621F470-9731-4A25-80EF-67A6F7C5F4B8");

            return client.RequestResourceOwnerPasswordAsync("bob", "secret", "WebApi1").Result;
        }
        static TokenResponse GetToken()
        {
            var client = new TokenClient(
                "https://localhost:44300/connect/token",
                "test",
                "secret");

            return client.RequestClientCredentialsAsync("api1").Result;
        }
Esempio n. 25
0
        static TokenResponse RequestToken()
        {
            var client = new TokenClient(
                Constants.TokenEndpoint,
                "roclient.reference",
                "secret");

            return client.RequestResourceOwnerPasswordAsync("bob", "bob", "api1").Result;
        }
        protected async Task<TokenResponse> GetTokenAsync()
        {
            string _url = Constants.IdentityServerUri + "/connect/token";
            var client = new TokenClient(
                _url,
                Constants.APIClient,
                Constants.IdentitySecret);

            return await client.RequestClientCredentialsAsync("apiAccess");
        }
Esempio n. 27
0
        static TokenResponse RequestToken()
        {
            var client = new TokenClient(
                Constants.TokenEndpoint,
                "roclient",
                "secret");

            //return client.RequestResourceOwnerPasswordAsync("wooboo","kop","read write").Result;
            return client.RequestResourceOwnerPasswordAsync("bubu","bubu","read write").Result;
        }
        static TokenResponse RequestToken()
        {
            var client = new TokenClient(
                Constants.TokenEndpoint,
                "clientcredentials.client",
                "secret",
                AuthenticationStyle.PostValues);

            return client.RequestClientCredentialsAsync("read write").Result;
        }
        public async Task<IHttpActionResult> Authenticate(AuthenticateRequest authenticateRequest)
        {
            var tokenClient = new TokenClient("https://localhost:44302/connect/token", "AngularClient", "secret");

            var result = await tokenClient.RequestResourceOwnerPasswordAsync(authenticateRequest.Username,authenticateRequest.Password, "Api"); //offline_access scope enables refresh token
            return Ok(new
            {
                result.AccessToken,
                result.RefreshToken
            });
        }
Esempio n. 30
0
        static string GetJwt()
        {
            var oauth2Client = new TokenClient(
                Constants.TokenEndpoint,
                "ro.client",
                "secret");

            var tokenResponse =
                oauth2Client.RequestResourceOwnerPasswordAsync("bob", "bob", "write").Result;

            return tokenResponse.AccessToken;
        }
Esempio n. 31
0
        private static async Task ExecuteAsync()
        {
            // discover endpoints from metadata
            var disco = await DiscoveryClient.GetAsync("http://localhost:5000");

            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }

            // request token
            Console.WriteLine("Requesting Token");
            var tokenClient   = new IdentityModel.Client.TokenClient(disco.TokenEndpoint, "apiclient", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            Console.WriteLine(tokenResponse.Json);

            // call api
            Console.WriteLine("Calling API");
            var client = new HttpClient();

            client.SetBearerToken(tokenResponse.AccessToken);

            var response = await client.GetAsync("http://localhost:5002/identity");

            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync();

                Console.WriteLine(JArray.Parse(content));
            }
            return;
        }
Esempio n. 32
0
        private static void Main()
        {
            Console.Write($"Please enter the Authority URL, press enter to use dev default or QUIT to exit{Environment.NewLine}>> ");
            var authorityUrl = Console.ReadLine();

            while (!authorityUrl.ToLower().Equals("quit"))
            {
                Console.Write($"Please enter the space separated API Scope(s){Environment.NewLine}>> ");
                var apiScope = Console.ReadLine();

                var discoveryResponse = DiscoveryClient.GetAsync(string.IsNullOrWhiteSpace(authorityUrl) ? "http://*****:*****@zupa.co.uk" : username,
                    string.IsNullOrWhiteSpace(password) ? "Password0-" : password,
                    apiScope).Result;

                Console.WriteLine(tokenResponseWithClaim.IsError
                    ? $"ERROR: {tokenResponseWithClaim.Error}"
                    : $"{Environment.NewLine}{tokenResponseWithClaim.Json}{Environment.NewLine}");

                Console.Write($"Please enter the Authority URL or QUIT to exit{Environment.NewLine}>> ");
                authorityUrl = Console.ReadLine();
            }
        }
Esempio n. 33
0
        /// <summary>
        /// Gets access token.
        /// </summary>
        /// <param name="address">
        /// Address of the service.
        /// </param>
        /// <param name="clientId">
        /// Client id.
        /// </param>
        /// <param name="clientSecret">
        /// Client secret.
        /// </param>
        /// <param name="extraData">
        /// Additional data to be sent.
        /// </param>
        /// <returns>
        /// An access token.
        /// </returns>
        public async Task <string> GetAccessTokenAsync(string address, string clientId, string clientSecret, object extraData)
        {
#pragma warning disable 618
            var client = new IdentityModelTokenClient.TokenClient(
#pragma warning restore 618
                address,
                clientId,
                clientSecret,
                this.ClientHandler)
            {
                BasicAuthenticationHeaderStyle = BasicAuthenticationHeaderStyle.Rfc2617,
            };

            var response = await client.RequestClientCredentialsAsync("identity request_claims", extraData);

            if (response.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new Exception($"Could not get access token from: {address} {response.HttpStatusCode} {response.ErrorDescription} {response.Json}");
            }

            return(response.AccessToken);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RefreshTokenDelegatingHandler"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="refreshToken">The refresh token.</param>
 /// <param name="accessToken">The access token.</param>
 public RefreshTokenDelegatingHandler(TokenClient client, string refreshToken, string accessToken)
 {
     _tokenClient  = client;
     _refreshToken = refreshToken;
     _accessToken  = accessToken;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AccessTokenDelegatingHandler"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="scope">The scope.</param>
 /// <param name="innerHandler">The inner handler.</param>
 public AccessTokenDelegatingHandler(TokenClient client, string scope, HttpMessageHandler innerHandler)
     : base(innerHandler)
 {
     _tokenClient = client;
     _scope       = scope;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AccessTokenDelegatingHandler"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="scope">The scope.</param>
 public AccessTokenDelegatingHandler(TokenClient client, string scope)
 {
     _tokenClient = client;
     _scope       = scope;
 }
Esempio n. 37
0
 public static Task <TokenResponse> RequestCustomAsync(this TokenClient client, object values, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(client.RequestAsync(Merge(client, ObjectToDictionary(values)), cancellationToken));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RefreshTokenDelegatingHandler"/> class.
 /// </summary>
 /// <param name="client">The client.</param>
 /// <param name="refreshToken">The refresh token.</param>
 /// <param name="innerHandler">The inner handler.</param>
 public RefreshTokenDelegatingHandler(TokenClient client, string refreshToken, HttpMessageHandler innerHandler)
     : base(innerHandler)
 {
     _tokenClient  = client;
     _refreshToken = refreshToken;
 }