Example #1
0
        //--- Methods ---
        protected override async Task OnInitializedAsync()
        {
            // remove any previous authentication tokens
            await LocalStorage.RemoveItemAsync("Tokens");

            // check if page is loaded with a authorization grant code (i.e. ?code=XYZ)
            var queryParameters = HttpUtility.ParseQueryString(new Uri(NavigationManager.Uri).Query);
            var code            = queryParameters["code"];

            if (!string.IsNullOrEmpty(code))
            {
                // ensure the replay guard matches
                var state = queryParameters["state"];
                if (!await VerifyReplayGuardAsync(state))
                {
                    // TODO: report login error to user
                    throw new NotImplementedException("replay guard failed");
                }

                // fetch the authorization token from Cognito
                Console.WriteLine($"Fetching authentication tokens for code grant: {code}");
                var oauth2TokenResponse = await HttpClient.PostAsync($"{CognitoSettings.UserPoolUri}/oauth2/token", new FormUrlEncodedContent(new[] {
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("client_id", CognitoSettings.ClientId),
                    new KeyValuePair <string, string>("redirect_uri", CognitoSettings.RedirectUri)
                }));

                if (oauth2TokenResponse.IsSuccessStatusCode)
                {
                    // store authentication tokens in local storage
                    var json = await oauth2TokenResponse.Content.ReadAsStringAsync();

                    Console.WriteLine($"Storing authentication tokens: {json}");
                    var authenticationTokens = AuthenticationTokens.FromJson(json);
                    await LocalStorage.SetItemAsync("Tokens", authenticationTokens);
                }
                else
                {
                    // TODO: report login error to user
                    throw new NotImplementedException("unable to retreive authentication tokens");
                }

                // navigate back to main page to connect to the websocket
                NavigationManager.NavigateTo("/");
            }
            else
            {
                Console.WriteLine("No code grant to fetch!");
                LoginUrl = CognitoSettings.GetLoginUrl("TBD");
            }
        }
Example #2
0
        private async Task <AuthenticationTokens> GetAuthenticationTokens()
        {
            // check if any authentication tokens are stored
            var authenticationTokens = await LoadTokensAsync();

            if (authenticationTokens == null)
            {
                LogInfo($"No authentication tokens found");
                return(null);
            }

            // check if tokens will expire in 5 minutes or less
            var authenticationTokenExpiration = DateTimeOffset.FromUnixTimeSeconds(authenticationTokens.Expiration);
            var authenticationTokenTtl        = authenticationTokenExpiration - DateTimeOffset.UtcNow;

            if (authenticationTokenTtl < TimeSpan.FromSeconds(TOKEN_EXPIRATION_LIMIT_SECONDS))
            {
                LogInfo($"Current authentication tokens has expired or expires soon: {authenticationTokenExpiration}");

                // refresh authentication tokens
                LogInfo($"Refreshing authentication tokens for code grant: {authenticationTokens.IdToken}");
                var oauth2TokenResponse = await HttpClient.PostAsync($"{CognitoSettings.UserPoolUri}/oauth2/token", new FormUrlEncodedContent(new[] {
                    new KeyValuePair <string, string>("grant_type", "refresh_token"),
                    new KeyValuePair <string, string>("client_id", CognitoSettings.ClientId),
                    new KeyValuePair <string, string>("refresh_token", authenticationTokens.RefreshToken)
                }));

                if (!oauth2TokenResponse.IsSuccessStatusCode)
                {
                    LogInfo("Authentication tokens refresh failed");
                    await ClearAuthenticationTokens();

                    return(null);
                }

                // store authentication tokens in local storage
                var json = await oauth2TokenResponse.Content.ReadAsStringAsync();

                LogInfo($"Storing authentication tokens: {json}");
                var refreshAuthenticationTokens = AuthenticationTokens.FromJson(json);
                authenticationTokens.IdToken     = refreshAuthenticationTokens.IdToken;
                authenticationTokens.AccessToken = refreshAuthenticationTokens.AccessToken;
                authenticationTokens.Expiration  = refreshAuthenticationTokens.Expiration;
                await SaveTokensAsync(authenticationTokens);
            }
            else
            {
                LogInfo($"Current authentication tokens valid until: {authenticationTokenExpiration}");
            }
            return(authenticationTokens);
        }