Example #1
0
        private async Task <bool> RefreshTokensAsync(CancellationToken cancellationToken)
        {
            var refreshToken = _sessionHandler.RefreshToken;

            if (string.IsNullOrWhiteSpace(refreshToken))
            {
                return(false);
            }

            if (await _lock.WaitAsync(Timeout, cancellationToken)
                .ConfigureAwait(false))
            {
                try
                {
                    var response = await _oidcClient.RefreshTokenAsync(refreshToken, cancellationToken : cancellationToken)
                                   .ConfigureAwait(false);

                    if (!response.IsError)
                    {
                        _sessionHandler.AccessToken = response.AccessToken;
                        if (!string.IsNullOrWhiteSpace(response.RefreshToken))
                        {
                            _sessionHandler.RefreshToken = response.RefreshToken;
                        }
                        return(true);
                    }
                }
                finally
                {
                    _lock.Release();
                }
            }

            return(false);
        }
        private async void _refreshButton_Click(object sender, EventArgs e)
        {
            if (_refreshToken != null)
            {
                var result = await _oidcClient.RefreshTokenAsync(_result.RefreshToken, null);

                Log("Refresh Token Result", clear: true);
                if (result.IsError)
                {
                    Log("Error: " + result.Error);
                    return;
                }

                _accessToken  = result.AccessToken;
                _refreshToken = result.RefreshToken;

                //_result.RefreshTokenHandler = result.RefreshToken;
                //_result.AccessToken = result.AccessToken;

                Log("Access Token: " + _accessToken);
                Log("Refresh Token: " + _refreshToken);
            }
            else
            {
                Log("No Refresh Token", true);
            }
        }
        private async void RefreshTokens(object sender, RoutedEventArgs e)
        {
            var options = new OidcClientOptions
            {
                Authority   = _authority,
                ClientId    = _clientIdentifier,
                RedirectUri = _redirectUri
            };
            var oidcClient = new OidcClient(options);
            var result     = await oidcClient.RefreshTokenAsync(_refreshToken);

            if (result.IsError)
            {
                Message.Text += string.Format("{0} - Refresh Tokens error: {1}\n", DateTime.Now, result.Error);
            }
            else
            {
                _accessToken  = result.AccessToken;
                _refreshToken = result.RefreshToken;
                Message.Text  = string.Format("{0} - Refresh completed successfully\n", DateTime.Now);
                Message.Text += string.Format("{0} - Identity token {1}\n Access token {2}\n"
                                              , DateTime.Now
                                              , JWTTokenHelper.ReadToken(_identityToken)
                                              , JWTTokenHelper.ReadToken(_accessToken));
            }
        }
Example #4
0
        private static async Task Refresh(string refreshToken, string resource)
        {
            var result =
                await _oidcClient.RefreshTokenAsync(refreshToken,
                                                    new BackChannelParameters { Resource = { resource } });

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

            Console.WriteLine();
            Console.WriteLine("down-scoped access token:");

            var parts   = result.AccessToken.Split('.');
            var header  = parts[0];
            var payload = parts[1];

            Console.WriteLine(Encoding.UTF8.GetString(Base64Url.Decode(header)).PrettyPrintJson());
            Console.WriteLine(Encoding.UTF8.GetString(Base64Url.Decode(payload)).PrettyPrintJson());

            Console.ReadLine();
        }
Example #5
0
        async Task <string> RefreshAccessToken(
            ISharedPreferences preferences,
            string refresh_token)
        {
            //Let's try refreshing the token
            var options = new OidcClientOptions
            {
                Authority    = "https://identity.provider.cotillo-corp.com",
                ClientId     = "android-app",
                ClientSecret = "VUdPR5HIlKLe4sVmMe6JbZk8v/JMZC5qy8VY2Chdfrg=",
                Scope        = "openid profile api1",
                RedirectUri  = "freemason://callback",
                Browser      = new BrowserCustomTabsWebView(this)
            };

            var client = new OidcClient(options);

            var token = await client.RefreshTokenAsync(refresh_token);

            //Let's update preference values

            UpdatePreferenceValues(
                preferences: preferences,
                access_token: token.AccessToken,
                refresh_token: token.RefreshToken,
                isRegistered: true);

            //Let's update the Bearer Token
            _apiClient.SetBearerToken(token.AccessToken);

            return(token.AccessToken);
        }
Example #6
0
        public async Task <string> WeatherForecast()
        {
            if (Settings.AccessTokenExpiration - DateTime.Now < TimeSpan.FromMinutes(1) && !String.IsNullOrWhiteSpace(Settings.RefreshToken))
            {
                var refreshResult = await OidcClient.RefreshTokenAsync(Settings.RefreshToken);

                if (refreshResult.IsError)
                {
                    Settings.AccessToken           = null;
                    Settings.AccessTokenExpiration = DateTime.Now;
                    Settings.RefreshToken          = null;
                }
                else
                {
                    Settings.AccessToken           = refreshResult.AccessToken;
                    Settings.AccessTokenExpiration = refreshResult.AccessTokenExpiration;
                    Settings.RefreshToken          = refreshResult.RefreshToken;
                }
            }
            HttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", Settings.AccessToken);

            var result = await HttpClient.GetAsync("WeatherForecast");

            var content = await result.Content.ReadAsStringAsync();

            if (result.IsSuccessStatusCode)
            {
                return(content);
            }
            else
            {
                return($"Status Code: {result.StatusCode}:\n{content}");
            }
        }
Example #7
0
        private static async Task NextSteps(LoginResult result)
        {
            var currentAccessToken  = result.AccessToken;
            var currentRefreshToken = result.RefreshToken;

            var menu = " x:exit \n b:call api All \n c:call api with route \n d:post api with body \n e:call api with query parameter";

            if (currentRefreshToken != null)
            {
                menu += "r:refresh token";
            }

            await CallApi(currentAccessToken);

            while (true)
            {
                Console.Write(menu);
                Console.Write("\n");
                var key = Console.ReadKey();

                if (key.Key == ConsoleKey.X)
                {
                    return;
                }
                if (key.Key == ConsoleKey.B)
                {
                    await CallApi(currentAccessToken);
                }
                if (key.Key == ConsoleKey.C)
                {
                    await CallApiwithRouteValue(currentAccessToken, "phil");
                }
                if (key.Key == ConsoleKey.D)
                {
                    await CallApiwithBodyValue(currentAccessToken, "mike");
                }
                if (key.Key == ConsoleKey.E)
                {
                    await CallApiwithQueryStringParam(currentAccessToken, "orange");
                }
                if (key.Key == ConsoleKey.R)
                {
                    var refreshResult = await _oidcClient.RefreshTokenAsync(currentRefreshToken);

                    if (result.IsError)
                    {
                        Console.WriteLine($"Error: {refreshResult.Error}");
                    }
                    else
                    {
                        currentRefreshToken = refreshResult.RefreshToken;
                        currentAccessToken  = refreshResult.AccessToken;

                        Console.WriteLine($"access token:   {result.AccessToken}");
                        Console.WriteLine($"refresh token:  {result?.RefreshToken ?? "none"}");
                    }
                }
            }
        }
        public static async void UseRefreshToken(this OidcClient client, string refreshToken)
        {
            var token = await client.RefreshTokenAsync(refreshToken);

            Console.WriteLine($"Access Token: {token.AccessToken}");
            Console.WriteLine($"Refresh Token: {token.RefreshToken}");
            Console.ReadLine();
        }
Example #9
0
        private static async Task NextSteps(LoginResult result)
        {
            var currentAccessToken  = result.AccessToken;
            var currentRefreshToken = result.RefreshToken;

            var menu = "  x...exit  c...call api   o..logout  ";

            if (currentRefreshToken != null)
            {
                menu += "r...refresh token   ";
            }

            while (true)
            {
                Console.WriteLine("\n\n");

                Console.Write(menu);
                var key = Console.ReadKey();

                if (key.Key == ConsoleKey.X)
                {
                    return;
                }
                if (key.Key == ConsoleKey.C)
                {
                    await CallApi(currentAccessToken);
                }
                if (key.Key == ConsoleKey.O)
                {
                    await _oidcClient.LogoutAsync();
                }
                if (key.Key == ConsoleKey.R)
                {
                    var refreshResult = await _oidcClient.RefreshTokenAsync(currentRefreshToken);

                    if (result.IsError)
                    {
                        Console.WriteLine($"Error: {refreshResult.Error}");
                    }
                    else
                    {
                        currentRefreshToken = refreshResult.RefreshToken;
                        currentAccessToken  = refreshResult.AccessToken;

                        Console.WriteLine("\n\n");
                        Console.WriteLine($"access token:   {result.AccessToken}");
                        Console.WriteLine($"refresh token:  {result?.RefreshToken ?? "none"}");
                    }
                }
            }
        }
Example #10
0
        private async Task refresh()
        {
            if (!allowRefresh)
            {
                return;
            }
            var refreshResult = await _oidcClient.RefreshTokenAsync(currentRefreshToken);

            if (!refreshResult.IsError)
            {
                currentRefreshToken = refreshResult.RefreshToken;
                currentAccessToken  = refreshResult.AccessToken;
            }
        }
Example #11
0
        public async Task <AccessTokenHolder> Activate(string refreshToken)
        {
            if (refreshToken != "")
            {
                var loginResponse = await client.RefreshTokenAsync(refreshToken);

                if (!loginResponse.IsError)
                {
                    return(new AccessTokenHolder(loginResponse.AccessToken, loginResponse.AccessTokenExpiration.DateTime,
                                                 loginResponse.RefreshToken));
                }
            }
            return(await DoUiLogin());
        }
Example #12
0
        /// <summary>
        /// Sign in using the supplied token and refresh token.
        /// </summary>
        /// <remarks>
        /// If <paramref name="token"/> is <see langword="null"/>,
        /// then <paramref name="refreshToken"/> will be used to
        /// get a new token.
        /// </remarks>
        /// <returns>Whether the sign-in succeeded.</returns>
        protected async Task <bool> SignInAsync(string token, string refreshToken)
        {
            try
            {
                Token        = token;
                RefreshToken = refreshToken;

                if (Token == null)
                {
                    // Use refresh token to get a new token
                    RefreshClient();
                    var resp = await _client.RefreshTokenAsync(RefreshToken);

                    if (!resp.IsError)
                    {
                        Token        = resp.AccessToken;
                        RefreshToken = resp.RefreshToken;
                    }
                    else
                    {
#if DEBUG
                        System.Diagnostics.Debug.WriteLine(resp.Error);
#endif
                    }
                }

                CurrentUser = await UpdateAccount();
                await OnSignInSuccess();

                if (RefreshToken != null)
                {
                    SaveCredential(RefreshToken);
                }

                IsLoggedIn = true;
            }
            catch (Exception ex)
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine(ex.Message);
#endif

                Token        = null;
                RefreshToken = null;
                IsLoggedIn   = false;
            }

            return(IsLoggedIn);
        }
        private async Task <AuthenticationInfo> RenewAuthAsync(String refreshToken)
        {
            var options = new OidcClientOptions
            {
                Authority    = UserSettings.Production ? "https://login.mhelpdesk.com/" : "https://preprod-login.mhelpdesk.com/",
                ClientId     = UserSettings.ApiKey,
                ClientSecret = UserSettings.ApiSecret,
                RedirectUri  = string.Format("http://127.0.0.1:54321/"),
                ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect,
                Scope        = "openid profile offline_access mhdapi",
                FilterClaims = true,
                LoadProfile  = true,
                Flow         = OidcClientOptions.AuthenticationFlow.AuthorizationCode,
                Policy       = new Policy()
                {
                    Discovery = new IdentityModel.Client.DiscoveryPolicy
                    {
                        ValidateIssuerName = false
                    }
                }
            };

            var client = new OidcClient(options);

            return(await Task.Run <AuthenticationInfo>(() =>
            {
                AuthenticationInfo newAuthInfo;
                try
                {
                    var result = client.RefreshTokenAsync(refreshToken).GetAwaiter().GetResult();
                    newAuthInfo = new AuthenticationInfo
                    {
                        AccessToken = result.AccessToken,
                        AccessTokenExpiration = result.AccessTokenExpiration,
                        RefreshToken = result.RefreshToken,
                        ApiKey = options.ClientId,
                    };
                }
                catch (Exception)
                {
                    newAuthInfo = null;
                }

                SaveAuthToFile(newAuthInfo);

                return newAuthInfo;
            }));
        }
Example #14
0
        private async Task <bool> RefreshTokensAsync(CancellationToken cancellationToken)
        {
            var refreshToken = RefreshToken;

            if (string.IsNullOrEmpty(refreshToken))
            {
                return(false);
            }

            if (await _lock.WaitAsync(_lockTimeout, cancellationToken).ConfigureAwait(false))
            {
                try
                {
                    // default IdentityModel way to refresh token
                    if (_tokenClient != null)
                    {
                        var response = await _tokenClient.RequestRefreshTokenAsync(refreshToken, cancellationToken : cancellationToken).ConfigureAwait(false);

                        if (!response.IsError)
                        {
                            _accessToken  = response.AccessToken;
                            _refreshToken = response.RefreshToken;
                            SaveToken();
                            return(true);
                        }
                    }
                    else
                    {
                        var client        = new OidcClient(GetIdentityOptions());
                        var refreshResult = await client.RefreshTokenAsync(refreshToken).ConfigureAwait(false);

                        if (!refreshResult.IsError)
                        {
                            _accessToken  = refreshResult.AccessToken;
                            _refreshToken = refreshResult.RefreshToken;
                            SaveToken();
                            return(true);
                        }
                    }
                }
                finally
                {
                    _lock.Release();
                }
            }

            return(false);
        }
Example #15
0
        private async Task RefreshToken()
        {
            try
            {
                var result =
                    await _oidcClient.RefreshTokenAsync(_refreshToken).ConfigureAwait(false);

                _accessToken  = result.AccessToken;
                _idToken      = result.IdentityToken;
                _refreshToken = result.RefreshToken;
                _expiry       = result.AccessTokenExpiration;
            }
            catch (Exception e)
            {
                throw new KubernetesClientException($"Unable to refresh OIDC token. \n {e.Message}", e);
            }
        }
Example #16
0
        public async Task <Credentials> RefreshToken(string refreshToken)
        {
            try
            {
                OidcClient         oidcClient         = CreateOidcClient();
                RefreshTokenResult refreshTokenResult = await oidcClient.RefreshTokenAsync(refreshToken);

                return(refreshTokenResult.ToCredentials());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(new Credentials {
                    Error = ex.ToString()
                });
            }
        }
        private async void RefreshButton_TouchUpInside(object sender, EventArgs e)
        {
            if (_user?.RefreshToken != null)
            {
                var result = await _client.RefreshTokenAsync(_user.RefreshToken);

                if (result.IsError)
                {
                    OutputText.Text = result.Error;
                    return;
                }

                _user.RefreshToken = result.RefreshToken;
                _user.AccessToken  = result.AccessToken;

                ShowUser();
            }
        }
Example #18
0
        /// <summary>
        /// Execute an Access token refresh, updating the data stores.
        /// <remarks>
        /// This method does not lock the tokenName semaphore, it is the responsibility of callers to ensure the semaphore is locked.
        /// </remarks>
        /// </summary>
        /// <param name="tokenName">Name of the token</param>
        /// <param name="refreshToken">The refresh token to use</param>
        /// <param name="replaceRefreshToken">Should the refresh token be replaced. This is required in case the server gives a new refresh token when the current one is used</param>
        /// <param name="options">Options for connecting to the Identity Server</param>
        /// <returns>New token unless refresh could not be carried out, then null</returns>
        private async Task <TokenData> ExecuteTokenRefreshAsync(string tokenName, string refreshToken,
                                                                bool replaceRefreshToken, OidcClientOptions options)
        {
            var client = new OidcClient(options);
            var result = await client.RefreshTokenAsync(refreshToken);

            if (result.IsError)
            {
                _log.Error("Error occured while trying to refresh Access Token. {Error}", result.Error);
                return(null);
            }

            // Save our tokens to the datastore
            if (replaceRefreshToken)
            {
                await UpdateRefreshTokenStorage(tokenName, result.RefreshToken);
            }

            return(await UpdateAccessTokenStorage(tokenName, result.AccessToken));
        }
Example #19
0
        public async Task <bool> RefreshAsync()
        {
            // Check secure storage for refresh token.
            EnsureAuthClient();
            RefreshTokenResult refreshResult = null;

            try
            {
                refreshResult = await _client.RefreshTokenAsync(RefreshToken);
            }
            catch (Exception e)
            {
                Debug.Log("UnityAuthClient::Exception during refresh: " + e.Message);
                return(false);
            }

            if (refreshResult.IsError)
            {
                Debug.Log("UnityAuthClient::Error authenticating: " + refreshResult.Error);
            }
            else
            {
                AccessToken           = refreshResult.AccessToken;
                RefreshToken          = refreshResult.RefreshToken;
                IdentityToken         = refreshResult.IdentityToken;
                AccessTokenExpiration = DateTime.Now.AddSeconds(refreshResult.ExpiresIn);

                KeyChain.SetString(refreshKey, RefreshToken);

                Debug.Log("UnityAuthClient::AccessToken: " + AccessToken);
                Debug.Log("UnityAuthClient::RefreshToken: " + RefreshToken);
                Debug.Log("UnityAuthClient::IdentityToken: " + IdentityToken);
                Debug.Log("UnityAuthClient::AccessTokenExpiration: " + AccessTokenExpiration);
                Debug.Log("UnityAuthClient::Refreshed.");
                return(true);
            }

            return(false);
        }
Example #20
0
        /// <summary>
        /// Refreshes and stores the new token in account storage.
        /// Returns account you can use to access api.
        /// </summary>
        /// <returns>Account.</returns>
        public async Task <Account> RefreshTokenAsync()
        {
            var account = await _accountStorageService.GetAccountAsync();

            if (account != null)
            {
                var refreshTokenResult = await _oidcClient.RefreshTokenAsync(account.RefreshToken);

                if (!refreshTokenResult.IsError)
                {
                    var newAccount = new Account
                    {
                        AccessToken  = refreshTokenResult.AccessToken,
                        RefreshToken = refreshTokenResult.RefreshToken,
                        Expiration   = refreshTokenResult.AccessTokenExpiration
                    };
                    await _accountStorageService.SetAccountAsync(newAccount);

                    return(newAccount);
                }
            }
            return(null);
        }
Example #21
0
        private async void RefreshTokens(object sender, EventArgs e)
        {
            var options = new OidcClientOptions
            {
                Authority   = _authority,
                ClientId    = _clientIdentifier,
                RedirectUri = _redirectUri
            };
            var oidcClient = new OidcClient(options);
            var result     = await oidcClient.RefreshTokenAsync(_refreshToken);

            if (result.IsError)
            {
                txtIdentityToken.Text = "Error";
                txtAccessToken.Text   = "Error";
            }
            else
            {
                _accessToken          = result.AccessToken;
                _refreshToken         = result.RefreshToken;
                txtIdentityToken.Text = JWTTokenHelper.ReadToken(_identityToken);
                txtAccessToken.Text   = JWTTokenHelper.ReadToken(_accessToken);
            }
        }
Example #22
0
        private static async Task NextSteps(LoginResult result)
        {
            var currentIdToken      = result.IdentityToken;
            var currentAccessToken  = result.AccessToken;
            var currentRefreshToken = result.RefreshToken;

            var menu = "  x...exit  l...get levels  d...query disciplines  ";

            if (currentRefreshToken != null)
            {
                menu += "r...refresh token  o...sign out ";
            }

            while (true)
            {
                Console.WriteLine("\n\n");

                Console.Write(menu);
                var key = Console.ReadKey();

                if (key.Key == ConsoleKey.X)
                {
                    return;
                }
                if (key.Key == ConsoleKey.L)
                {
                    await GetLevels(currentAccessToken);
                }
                if (key.Key == ConsoleKey.D)
                {
                    await QueryDisciplines(currentAccessToken);
                }
                if (key.Key == ConsoleKey.R)
                {
                    var refreshResult = await _oidcClient.RefreshTokenAsync(currentRefreshToken);

                    if (refreshResult.IsError)
                    {
                        Console.WriteLine($"Error: {refreshResult.Error}");
                    }
                    else
                    {
                        currentRefreshToken = refreshResult.RefreshToken;
                        currentAccessToken  = refreshResult.AccessToken;

                        Console.WriteLine("\n\n");
                        Console.WriteLine($"access token:   {currentAccessToken}");
                        Console.WriteLine($"refresh token:  {currentRefreshToken ?? "none"}");
                    }
                }
                if (key.Key == ConsoleKey.O)
                {
                    // Get the URI for the Revocation Endpoint
                    var disco = await _apiClient.GetDiscoveryDocumentAsync(_authority);

                    if (disco.IsError)
                    {
                        Console.WriteLine("Failed to access Discovery Document");
                        break;
                    }

                    // Revoke the Refresh Token
                    var revokeResult = await _apiClient.RevokeTokenAsync(new TokenRevocationRequest
                    {
                        Address       = disco.RevocationEndpoint,
                        ClientId      = _clientId,
                        Token         = currentRefreshToken,
                        TokenTypeHint = "refresh_token"
                    });

                    // Sign out from the ID Server
                    await _oidcClient.LogoutAsync(new LogoutRequest
                    {
                        IdTokenHint = currentIdToken
                    });
                }
            }
        }
Example #23
0
        private async static Task SignInAsync()
        {
            // create a redirect URI using an available port on the loopback address.
            string redirectUri = string.Format("http://127.0.0.1:7890/");

            // create an HttpListener to listen for requests on that redirect URI.
            var settings = new WebListenerSettings();

            settings.UrlPrefixes.Add(redirectUri);
            var http = new WebListener(settings);

            http.Start();
            Console.WriteLine("Listening..");

            var options = new OidcClientOptions
            {
                Authority    = _authority,
                ClientId     = "native.hybrid",
                RedirectUri  = redirectUri,
                Scope        = "openid profile offline_access read api",
                ClientSecret = "secret",
                FilterClaims = true,
                LoadProfile  = true,
                Flow         = OidcClientOptions.AuthenticationFlow.Hybrid
            };

            var serilog = new LoggerConfiguration()
                          .MinimumLevel.Verbose()
                          .Enrich.FromLogContext()
                          .WriteTo.LiterateConsole(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}")
                          .CreateLogger();

            options.LoggerFactory.AddSerilog(serilog);

            var client = new OidcClient(options);
            var state  = await client.PrepareLoginAsync();

            OpenBrowser(state.StartUrl);

            var context = await http.AcceptAsync();

            var formData = GetRequestPostData(context.Request);

            if (formData == null)
            {
                Console.WriteLine("Invalid response");
                return;
            }

            await SendResponseAsync(context.Response);

            var result = await client.ProcessResponseAsync(formData, state);

            options.Policy.ForceIntrospectionForAccessToken = true;
            //-- Test POP generation
            var testPop = client.CreatePopToken(new IdentityModel.OidcClient.Pop.EncodingParameters(options, result.AccessToken)
            {
                Method = "GET"
            }.ToJwtPayload(), result.PopTokenKey).ToSignedB64String();

            Console.WriteLine($"Generated PoP Token: {testPop}");

            //--Test validation...
            var testValidate = await client.ValidatePopToken(testPop, false, "read", "secret");

            Console.WriteLine($"PoP Token Valid: {!testValidate.IsError}");

            //--Test refresh
            var refreshResult = await client.RefreshTokenAsync(result.RefreshToken);

            var refreshValidate = client.CreatePopToken(new IdentityModel.OidcClient.Pop.EncodingParameters(options, refreshResult.AccessToken)
            {
                Method = "GET"
            }.ToJwtPayload(), refreshResult.PopTokenKey).ToSignedB64String();
            var refreshValid = await client.ValidatePopToken(refreshValidate, false, "read", "secret");

            var oldValidate = client.CreatePopToken(new IdentityModel.OidcClient.Pop.EncodingParameters(options, result.AccessToken)
            {
                Method = "GET"
            }.ToJwtPayload(), result.PopTokenKey).ToSignedB64String();
            var oldValid = await client.ValidatePopToken(oldValidate, false, "read", "secret");

            Console.WriteLine($"Generated PoP Token after refresh: {testPop}");
            Console.WriteLine($"PoP Token (using refreshed access token) Valid: {!refreshValid.IsError}");
            Console.WriteLine($"PoP Token (using old access token) Valid: {!oldValid.IsError}"); //Depending on how implemented - this should not work for an old token after the refresh token has been used.

            //--Revoke the tokens.
            var revokeClient = new TokenRevocationClient($"{options.Authority}/connect/revocation", options.ClientId, options.ClientSecret);
            var revokeResult = await revokeClient.RevokeRefreshTokenAsync(refreshResult.RefreshToken);

            Console.WriteLine($"Token revocation succeeded: {!revokeResult.IsError}");

            ShowResult(result);
        }
Example #24
0
        private static async Task NextSteps(LoginResult result)
        {
            var currentAccessToken  = result.AccessToken;
            var currentRefreshToken = result.RefreshToken;

            var menu = "- [G]et SCIM Users\n";

            if (currentRefreshToken != null)
            {
                menu += "- [R]efresh token\n";
            }
            menu += "- [E]xit\n";
            menu += "Press key: ";

            while (true)
            {
                Console.WriteLine("\n\n");

                Console.Write(menu);
                ConsoleKeyInfo key = Console.ReadKey();

                if (key.Key == ConsoleKey.E)
                {
                    return;
                }
                if (key.Key == ConsoleKey.G)
                {
                    await CallApi(currentAccessToken);
                }
                if (key.Key == ConsoleKey.R)
                {
                    IdentityModel.OidcClient.Results.RefreshTokenResult refreshResult = await s_oidcClient.RefreshTokenAsync(currentRefreshToken);

                    if (refreshResult.IsError)
                    {
                        Console.WriteLine($"Error: {refreshResult.Error}");
                    }
                    else
                    {
                        currentRefreshToken = refreshResult.RefreshToken;
                        currentAccessToken  = refreshResult.AccessToken;

                        Console.WriteLine("\n\n");
                        Console.WriteLine($"Access token:   {currentAccessToken}");
                        Console.WriteLine($"Refresh token:  {currentRefreshToken ?? "none"}");
                    }
                }
            }
        }
Example #25
0
        /// <inheritdoc />
        public virtual async Task <AccessTokenResult> RequestAccessToken()
        {
            await EnsureAuthService();

            if (await TokenCache.TryGet(AccessTokenKey, out var accessToken))
            {
                return(new AccessTokenResult(this, AccessTokenResultStatus.Success, new AccessToken()
                {
                    Expires = accessToken.ValidTo.ToLocalTime(),
                    GrantedScopes = accessToken.Claims.Where(x => x.Type.Equals(Options.UserOptions.ScopeClaim, StringComparison.Ordinal)).Select(x => x.Value).ToList(),
                    Value = accessToken.RawData,
                }));
            }

            Task <Task <AccessTokenResult> > requestAccessTokenTask = null;

            // make sure we execute this method only once. We await the task otherwise.
            // With multiple components requesting the authentication state during reload, this happens. Multiple requests would be sent to the authentication
            // service with possible loss of the last refresh/or auth token.
            if ((requestAccessTokenTask = Interlocked.CompareExchange(ref _requestAccessTokenTask, new Task <Task <AccessTokenResult> >(InternalRequestAccessToken), null)) == null)
            {
                requestAccessTokenTask = _requestAccessTokenTask;
                requestAccessTokenTask.Start();
            }

            return(await requestAccessTokenTask.Unwrap());

            async Task <AccessTokenResult> InternalRequestAccessToken()
            {
                try
                {
                    string refreshToken = null;

                    if (!string.IsNullOrEmpty(refreshToken = await _protectedStorage.GetAsync <string>(RefreshTokenKey)))
                    {
                        var refreshTokenResult = await Client.RefreshTokenAsync(refreshToken);

                        if (refreshTokenResult.IdentityToken != null)
                        {
                            await TokenCache.Add(IdTokenKey, new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(refreshTokenResult.IdentityToken));
                        }
                        if (refreshTokenResult.RefreshToken != null)
                        {
                            await _protectedStorage.SetAsync(RefreshTokenKey, refreshTokenResult.RefreshToken);
                        }
                        if (refreshTokenResult.AccessToken != null)
                        {
                            accessToken = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(refreshTokenResult.AccessToken);
                            await TokenCache.Add(AccessTokenKey, accessToken);

                            var grantedScopes = accessToken.Claims.Where(x => x.Type.Equals(Options.UserOptions.ScopeClaim, StringComparison.Ordinal)).Select(x => x.Value).ToList();

                            return(new AccessTokenResult(this, AccessTokenResultStatus.Success, new AccessToken()
                            {
                                Expires = accessToken.ValidTo.ToLocalTime(),
                                GrantedScopes = grantedScopes,
                                Value = accessToken.RawData,
                            }));
                        }
                    }

                    return(new AccessTokenResult(this, AccessTokenResultStatus.RequiresRedirect, null));
                }
                finally
                {
                    _requestAccessTokenTask = null;
                }
            }
        }
Example #26
0
        public async Task <RefreshTokenResult> RefreshTokenAsync(string refreshToken)
        {
            var client = new OidcClient(CreateBaseOptions());

            return(await client.RefreshTokenAsync(refreshToken));
        }