private void ValidateResponseAndSignIn(TokenResponse response)
        {
            if (!string.IsNullOrWhiteSpace(response.IdentityToken))
            {
                var tokenClaims = ValidateToken(response.IdentityToken);
                var claims = new List<Claim>(from c in tokenClaims
                                             where c.Type != "iss" &&
                                                   c.Type != "aud" &&
                                                   c.Type != "nbf" &&
                                                   c.Type != "exp" &&
                                                   c.Type != "iat" &&
                                                   c.Type != "amr" &&
                                                   c.Type != "idp"
                                             select c);


                if (!string.IsNullOrWhiteSpace(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);
            }
        }
        static void CallApi(TokenResponse response)
        {
            var client = new HttpClient();
            client.SetBearerToken(response.AccessToken);

            Console.WriteLine(client.GetStringAsync("http://localhost:14869/test").Result);
        }
 Authenticator(Authenticator authenticator, TokenResponse tokenResponse)
 {
     this.authorizationEndpoint = new Uri(authenticator.options.Authority, "connect/token");
     this.options = authenticator.options;
     current = tokenResponse;
     InitializedAt = DateTime.UtcNow;
 }
        static String CallApi(TokenResponse response)
        {
            var client = new HttpClient();
            client.SetBearerToken(response.AccessToken);

            return client.GetStringAsync(Constants.ApiUrl + "/test").Result;
        }
        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);
                }
            }
        }
Exemple #6
0
        public async static Task<TokenResponse> RefreshToken(TokenResponse token)
        {
            var client = new OAuth2Client(
                 new Uri(Constant.TokenEndpoint),
                 Constant.CodeClientId,
                 Constant.CodeClientSecret);

            return await client.RequestRefreshTokenAsync(token.RefreshToken);
        }
        public async void Login()
        {
            token = GetToken(UserName, Password);

            if(!token.IsError)
            {
                LijstLogs = await GetLogs(token.AccessToken);
            }
        }
        static void CallApi(TokenResponse response)
        {
            var client = new HttpClient();
            client.SetBearerToken(response.AccessToken);
            Console.WriteLine("Calling api...");
            var result = client.GetStringAsync("http://localhost:47922/test").Result;
            Console.WriteLine("API called...");
            Console.WriteLine(result);

            //WebClient client = new WebClient();
            //client.Headers["Authorization"] = "Bearer " + response.AccessToken;
            //var result = client.DownloadString("http://localhost:47922/test");
            //Console.WriteLine("Result: " + result);
        }
        private void UpdateCookie(TokenResponse response)
        {
            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 void ValidateResponseAndSignIn(TokenResponse response)
        {
            if (!string.IsNullOrWhiteSpace(response.IdentityToken))
            {
                var claims = ValidateToken(response.IdentityToken);

                if (!string.IsNullOrWhiteSpace(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);
            }
        }
        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);
            }
        }
Exemple #12
0
        private static TokenResponse RefreshToken(TokenResponse resultToken)
        {
            Console.WriteLine("\n--------------------------------");
            Console.WriteLine("Refresh Token\n{0}\n", resultToken.RefreshToken);

            TokenResponse refreshedToken = null;
            try
            {
                refreshedToken = Util.RefreshToken(resultToken).Result;
            }
            catch (AggregateException ex)
            {
                if (ex.InnerException.GetType() == typeof (HttpRequestException))
                {
                    Console.WriteLine("Exception: {0}", ex.InnerException.Message);
                    Console.Write("Refresh Token expired?");
                }
                else
                {
                    throw;
                }
            }
            return refreshedToken;
        }
Exemple #13
0
        public static void ParseToken(TokenResponse token)
        {
            var handler = new JwtSecurityTokenHandler();
            var decodedToken = handler.ReadToken(token.AccessToken) as JwtSecurityToken;

            Console.WriteLine("--------------------------------");
            Console.WriteLine("Access Token:\n{0}\n\n", token.AccessToken);
            Console.WriteLine("Refresh Token:\n{0}\n\n", token.RefreshToken);
            Console.WriteLine("Token Type:\n{0}\n", token.TokenType);

            Console.WriteLine("Issuer:\n{0}\n", decodedToken.Issuer);
            Console.WriteLine("Audience:\n{0}\n", decodedToken.Audience);
            Console.WriteLine("Valid:\n{0} - {1}\n", decodedToken.ValidFrom, decodedToken.ValidTo);
            Console.WriteLine("User:\n{0}\n", decodedToken.Subject);
            Console.WriteLine("Scopes:");
            foreach (var cl in decodedToken.Claims.Where(c => c.Type == "scope"))
            {
                Console.Write("{0} ", cl.Value);
            }
            Console.WriteLine("\n\n--------------------------------");
        }
Exemple #14
0
        private static bool SendRessourceRequest(TokenResponse accessToken, string requestPath)
        {
            var request = (HttpWebRequest) WebRequest.Create(requestPath);

            request.Headers.Add("Authorization", "Bearer " + accessToken.AccessToken);
            request.ContentType = "application/xml";

            try
            {
                var response = (HttpWebResponse) request.GetResponse();
                ReadXml(response);
                return true;
            }
            catch (WebException ex)
            {
                var statusCode = (int) ((HttpWebResponse) ex.Response).StatusCode;

                if (statusCode != 403) // Forbidden access code, sendt by the ressource server when the token expired
                {
                    throw new Exception("Token validation failed", ex);
                }
                // token invalid (403)
                return false;
            }
        }
Exemple #15
0
        private static void RequestRessources(TokenResponse accessToken)
        {
            var regex = @"^\d{1,3}$";
            var validInput = false;
            string userinput;
            do
            {
                Console.Write("ID des Datensatzes auf Ressource Server angeben (0 für alle): ");
                userinput = Console.ReadLine();
                if (userinput != null)
                {
                    validInput = Regex.Match(userinput, regex).Success;
                }
            } while (!validInput);

            var requestId = Convert.ToInt32(userinput);

            var requestPath = requestId == 0 ? Constant.RessourceUrl : Constant.RessourceUrl + requestId ;

            var tokenValid = SendRessourceRequest(accessToken, requestPath);

            if (tokenValid == false)
            {
                Console.WriteLine("Token invalid, trying to refresh access token...");
                var refreshedToken = Util.RefreshToken(accessToken).Result;
                var newTokenValid = SendRessourceRequest(refreshedToken, requestPath);

                if (newTokenValid == false)
                {
                    Console.WriteLine("Refresh token expired or access token invalid");
                }
            }
        }
 static void CallApi(TokenResponse response)
 {
     var client = new HttpClient();
     client.SetBearerToken(response.AccessToken);
     System.Console.WriteLine(client.GetStringAsync(ApplicationConstants.UrlBaseApi + "/api/values").Result);
 }
		private void SaveTokenToLocalStorage(TokenResponse token)
		{
			var storageItem = new InternalTokenStorageItem()
			{
				Token = token.AccessToken,
				AbsoluteExpirationDate = DateTime.Now.AddMilliseconds(token.ExpiresIn * 1000),
			};

			_storage.SaveTo(StorageFileName, storageItem);
		}
 public InvalidRefreshTokenException(TokenResponse tokenResponse)
 {
     TokenResponse = tokenResponse;
 }
 public Authenticator(Options options)
 {
     this.authorizationEndpoint = new Uri(options.Authority, "connect/token");
     this.options = options;
     current = new TokenResponse(HttpStatusCode.Unauthorized, "Unauthorized");
 }