Esempio n. 1
10
        private static void ShowResponse(TokenResponse response)
        {
            if (!response.IsError)
            {
                "Token response:".ConsoleGreen();
                Console.WriteLine(response.Json);

                if (response.AccessToken.Contains("."))
                {
                    "\nAccess Token (decoded):".ConsoleGreen();

                    var parts = response.AccessToken.Split('.');
                    var header = parts[0];
                    var claims = parts[1];

                    Console.WriteLine(JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(header))));
                    Console.WriteLine(JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(claims))));
                }
            }
            else
            {
                if (response.IsHttpError)
                {
                    "HTTP error: ".ConsoleGreen();
                    Console.WriteLine(response.HttpErrorStatusCode);
                    "HTTP error reason: ".ConsoleGreen();
                    Console.WriteLine(response.HttpErrorReason);
                }
                else
                {
                    "Protocol error response:".ConsoleGreen();
                    Console.WriteLine(response.Json);
                }
            }
        }
Esempio n. 2
0
        static void CallApi(TokenResponse response)
        {
            var client = new HttpClient();
            client.SetBearerToken(response.AccessToken);

            Console.WriteLine(client.GetStringAsync("http://localhost:14869/test").Result);
        }
Esempio n. 3
0
 private ApiResponse(TokenResponse response) {
     AccessToken = response.AccessToken;
     ExpiresIn = response.ExpiresIn;
     RefreshToken = response.RefreshToken;
     TokenType = response.TokenType;
     IsError = response.IsError;
     Error = response.Error;
 }
        private Dictionary <string, object> GetPayload(IdentityModel.Client.TokenResponse response)
        {
            var token      = response.AccessToken.Split('.').Skip(1).Take(1).First();
            var dictionary = JsonConvert.DeserializeObject <Dictionary <string, object> >(
                Encoding.UTF8.GetString(Base64Url.Decode(token)));

            return(dictionary);
        }
Esempio n. 5
0
        private async Task <TokenResponse> GrantInitTokens(string email, string password, int allowedFailAttempts = 3)
        {
            var disco = await DiscoveryClient.GetAsync(_config.Value.IdentityServerUrl);

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

            var tokenClient = new TokenClient(disco.TokenEndpoint, _clientIdSecretConfigs.Value.AppClientId, _clientIdSecretConfigs.Value.AppClientSecret);

            TokenResponse tokenResponse   = null;
            var           grantAttempts   = 0;
            var           grantSuccessful = false;

            while (!grantSuccessful)
            {
                tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync(email, password);

                if (!tokenResponse.IsError)
                {
                    grantSuccessful = true;
                }
                else
                {
                    grantAttempts++;
                    await Task.Delay(100);

                    if (grantAttempts >= allowedFailAttempts)
                    {
                        break;
                    }
                }
            }

            return(tokenResponse);
        }
Esempio n. 6
0
        public async Task <string> GetAccessToken()
        {
            _logger.LogInformation("Starting Get AccessToken from https://latinonetonlineidentityserver.herokuapp.com");
            string host = "https://latinonetonlineidentityserver.herokuapp.com";
            DiscoveryDocumentResponse discoveryDocument = await _httpClient.GetDiscoveryDocumentAsync(
                new DiscoveryDocumentRequest
            {
                Address = host,
                Policy  =
                {
                    ValidateIssuerName = false
                }
            });

            if (discoveryDocument.IsError)
            {
                throw new Exception("error");
            }

            ClientCredentialsTokenRequest clientCredentialsTokenRequest = new ClientCredentialsTokenRequest
            {
                Address      = discoveryDocument.TokenEndpoint,
                GrantType    = GrantTypes.ClientCredentials,
                ClientId     = "schedule-job-client",
                ClientSecret = _identityClientSecret
            };

            IdentityModel.Client.TokenResponse TokenResponse = await _httpClient.RequestClientCredentialsTokenAsync(clientCredentialsTokenRequest);

            if (TokenResponse.IsError)
            {
                throw new Exception("error");
            }

            _logger.LogInformation("Get Access Token successfuly");

            return(TokenResponse.AccessToken);
        }
        private void UpdateCookie(TokenResponse response)
        {
            if (response.IsError)
            {
                throw new Exception(response.Error);
            }

            var identity = (User as ClaimsPrincipal).Identities.First();
            var result = from c in identity.Claims
                         where c.Type != "access_token" &&
                               c.Type != "refresh_token" &&
                               c.Type != "expires_at"
                         select c;

            var claims = result.ToList();

            claims.Add(new Claim("access_token", response.AccessToken));
            claims.Add(new Claim("expires_at", (DateTime.UtcNow.ToEpochTime() + response.ExpiresIn).ToDateTimeFromEpoch().ToString()));
            claims.Add(new Claim("refresh_token", response.RefreshToken));
            
            var newId = new ClaimsIdentity(claims, "Cookies");
            Request.GetOwinContext().Authentication.SignIn(newId);
        }
        private async Task ValidateResponseAndSignInAsync(TokenResponse response, string nonce)
        {
            if (!string.IsNullOrWhiteSpace(response.IdentityToken))
            {
                var tokenClaims = ValidateToken(response.IdentityToken, nonce);
                var claims = new List<Claim>();

                if (!string.IsNullOrWhiteSpace(response.AccessToken))
                {
                    claims.AddRange(await GetUserInfoClaimsAsync(response.AccessToken));

                    claims.Add(new Claim("access_token", response.AccessToken));
                    claims.Add(new Claim("expires_at", (DateTime.UtcNow.ToEpochTime() + response.ExpiresIn).ToDateTimeFromEpoch().ToString()));
                }

                if (!string.IsNullOrWhiteSpace(response.RefreshToken))
                {
                    claims.Add(new Claim("refresh_token", response.RefreshToken));
                }

                var id = new ClaimsIdentity(claims, "Cookies");
                Request.GetOwinContext().Authentication.SignIn(id);
            }
        }
 public Tokens(IdentityModel.Client.TokenResponse response)
 {
     AccessToken  = response.AccessToken;
     RefreshToken = response.RefreshToken;
 }
 public Task<IResponse> RequestTokenAsync(string userName, string password) {
     TokenResponse response = new TokenResponse(JsonConvert.SerializeObject(new { access_token = "test" }));
     return Task.FromResult(ApiResponse.FromTokenResponse(response));
 }
        private Dictionary<string, object> GetPayload(TokenResponse response)
        {
            var token = response.AccessToken.Split('.').Skip(1).Take(1).First();
            var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(
                Encoding.UTF8.GetString(Base64Url.Decode(token)));

            return dictionary;
        }
Esempio n. 12
0
 /// <summary>
 /// Creates an <see cref="IResponse"/> from the specified token response.
 /// </summary>
 /// <param name="response">The token response.</param>
 /// <returns>A <see cref="IResponse"/> indicating a account Api response.</returns>
 public static IResponse FromTokenResponse(TokenResponse response) => new ApiResponse(response);
Esempio n. 13
0
 public Tokens(TokenResponse response)
 {
     AccessToken  = response.AccessToken;
     RefreshToken = response.RefreshToken;
 }
Esempio n. 14
0
        /// <summary>
        /// Try logging in using the tokens stored in the password vault.
        /// </summary>
        /// <returns></returns>
        private async System.Threading.Tasks.Task<bool> TryLoginUsingVaultAsync()
        {
            var raw = ApiService.GetTokenFromVault();
            if (string.IsNullOrEmpty(raw))
            {
                ApiService.RemoveTokenFromVault();
                return false;
            }

            var tokenResponse = new TokenResponse(raw);
            if (await FinishLoginAsync(tokenResponse))
            {
                return true;
            }

            // If logging on fails, remove the token from the vault.
            ApiService.RemoveTokenFromVault();
            return false;
        }
Esempio n. 15
0
        private async System.Threading.Tasks.Task<bool> FinishLoginAsync(TokenResponse response)
        {
            // Let's retrieve the claims using that access token to fetch the user name we need.
            // Note: the user name is already in our response's access token, but this code demonstrates retrieving all claims.
            var userInfoRequest = new UserInfoClient(new Uri(TimesheetConstants.UserInfoEndpoint), response.AccessToken);
            var userInfo = await userInfoRequest.GetAsync();

            if (userInfo.IsError || userInfo.IsHttpError)
            {
                return false;
            }

            // Set the EmployeeId needed to create time registrations.
            App.EmployeeId = userInfo.Claims.FirstOrDefault(x => x.Item1 == "name")?.Item2 ?? "";

            // Remember the access token when calling the API
            _apiService.TokenResponse = response;

            NavigateToDetailPage();
            return true;
        }
 public  ActionResult SignInToken(TokenResponse token)
 {
     return View(token);
 }
 public Task<IResponse> RefreshTokenAsync(string refreshToken) {
     TokenResponse response = new TokenResponse(JsonConvert.SerializeObject(new { access_token = "test" }));
     return Task.FromResult(ApiResponse.FromTokenResponse(response));
 }