public async ValueTask <AccessTokenResult> RequestAccessToken(AccessTokenRequestOptions options)
        {
            var tokenObject = await _localStorage.GetItemAsync <TokenObject>("token");

            if (tokenObject != null && tokenObject.Token != null)
            {
                var now = DateTimeOffset.Now;

                if (now >= tokenObject.tokenExpirationTime.AddSeconds(-30))
                {
                    if (await _authenticationService.RefreshToken())
                    {
                        tokenObject = await _localStorage.GetItemAsync <TokenObject>("token");
                    }
                    else
                    {
                        throw new Exception("refresh token failed");
                    }
                }

                var token = new AccessToken {
                    Value = tokenObject.Token, Expires = tokenObject.tokenExpirationTime
                };

                var accessTokenResult = new AccessTokenResult(AccessTokenResultStatus.Success, token, "");

                return(accessTokenResult);
            }

            return(null);
        }
Exemple #2
0
        /// <inheritdoc />
        public async Task <AccessTokenResult> RequestAccessToken(AccessTokenRequestOptions options)
        {
            if (_currentAccount == null)
            {
                var accounts = await _clientApplication.GetAccountsAsync().ConfigureAwait(false);

                if (accounts.Any())
                {
                    _currentAccount = accounts.First();
                }
                else
                {
                    return(new AccessTokenResult(this, AccessTokenResultStatus.RequiresRedirect, null));
                }
            }
            AuthenticationResult result = null;

            try
            {
                result = await _clientApplication
                         .AcquireTokenSilent(_currentScopes = options?.Scopes != null?_currentScopes.Union(options.Scopes) : _currentScopes, _currentAccount)
                         .ExecuteAsync()
                         .ConfigureAwait(false);
            }
            catch (MsalUiRequiredException)
            {
            }

            if (result == null)
            {
                return(new AccessTokenResult(this, AccessTokenResultStatus.RequiresRedirect, null));
            }

            if (!string.IsNullOrEmpty(result.IdToken))
            {
                _idToken = new JwtSecurityToken(result.IdToken);
            }

            _currentScopes = result.Scopes;

            return(new AccessTokenResult(this, AccessTokenResultStatus.Success, new AccessToken()
            {
                Expires = result.ExpiresOn,
                GrantedScopes = result.Scopes.ToList(),
                Value = result.AccessToken,
            }));
        }
Exemple #3
0
        /// <summary>
        /// Configures this handler to authorize outbound HTTP requests using an access token. The access token is only attached if at least one of
        /// <paramref name="authorizedUrls" /> is a base of <see cref="HttpRequestMessage.RequestUri" />.
        /// </summary>
        /// <param name="authorizedUrls">The base addresses of endpoint URLs to which the token will be attached.</param>
        /// <param name="scopes">The list of scopes to use when requesting an access token.</param>
        /// <param name="returnUrl">The return URL to use in case there is an issue provisioning the token and a redirection to the
        /// identity provider is necessary.
        /// </param>
        /// <param name="authenticationScheme">
        /// The authentication scheme to be used with in Authorization, ProxyAuthorization, WWW-Authenticate, and Proxy-Authenticate headers.
        /// Defaults to 'Bearer'.
        /// </param>
        /// <returns>This <see cref="AuthorizationMessageHandler"/>.</returns>
        public AuthorizationMessageHandler ConfigureHandler(
            IEnumerable <string> authorizedUrls,
            IEnumerable <string> scopes = null,
            string returnUrl            = null,
            string authenticationScheme = null)
        {
            if (_authorizedUris != null)
            {
                throw new InvalidOperationException("Handler already configured.");
            }

            if (authorizedUrls == null)
            {
                throw new ArgumentNullException(nameof(authorizedUrls));
            }

            var uris = authorizedUrls.Select(uri => new Uri(uri, UriKind.Absolute)).ToArray();

            if (uris.Length == 0)
            {
                throw new ArgumentException("At least one URL must be configured.", nameof(authorizedUrls));
            }

            _authorizedUris = uris;
            var scopesList = scopes?.ToArray();

            if (scopesList != null || returnUrl != null)
            {
                _tokenOptions = new AccessTokenRequestOptions
                {
                    Scopes    = scopesList,
                    ReturnUrl = returnUrl
                };
            }

            if (!string.IsNullOrWhiteSpace(authenticationScheme))
            {
                _authenticationScheme = authenticationScheme;
            }

            return(this);
        }
Exemple #4
0
    public virtual async ValueTask <AccessTokenResult> RequestAccessToken(AccessTokenRequestOptions options)
    {
        if (options is null)
        {
            throw new ArgumentNullException(nameof(options));
        }

        await EnsureAuthService();

        var result = await JsRuntime.InvokeAsync <InternalAccessTokenResult>("AuthenticationService.getAccessToken", options);

        return(new AccessTokenResult(
                   result.Status,
                   result.Token,
                   result.Status == AccessTokenResultStatus.RequiresRedirect ? Options.AuthenticationPaths.LogInPath : null,
                   result.Status == AccessTokenResultStatus.RequiresRedirect ? new InteractiveRequestOptions
        {
            Interaction = InteractionType.GetToken,
            ReturnUrl = GetReturnUrl(options.ReturnUrl),
            Scopes = options.Scopes ?? Array.Empty <string>(),
        } : null));
    }
    public async Task RemoteAuthenticationService_GetAccessToken_PassesDownOptions()
    {
        // Arrange
        var testJsRuntime = new TestJsRuntime();
        var options       = CreateOptions();
        var runtime       = new RemoteAuthenticationService <RemoteAuthenticationState, RemoteUserAccount, OidcProviderOptions>(
            testJsRuntime,
            options,
            new TestNavigationManager(),
            new AccountClaimsPrincipalFactory <RemoteUserAccount>(Mock.Of <IAccessTokenProviderAccessor>()));

        var state = new RemoteAuthenticationState();

        testJsRuntime.GetAccessTokenResult = new InternalAccessTokenResult
        {
            Status = "requiresRedirect",
        };

        var tokenOptions = new AccessTokenRequestOptions
        {
            Scopes = new[] { "something" }
        };

        var expectedRedirectUrl = "https://www.example.com/base/login?returnUrl=https%3A%2F%2Fwww.example.com%2Fbase%2Fadd-product";

        // Act
        var result = await runtime.RequestAccessToken(tokenOptions);

        // Assert
        Assert.Equal(
            new[] { "AuthenticationService.init", "AuthenticationService.getAccessToken" },
            testJsRuntime.PastInvocations.Select(i => i.identifier).ToArray());

        Assert.False(result.TryGetToken(out var token));
        Assert.Null(token);
        Assert.Equal(result.Status, Enum.Parse <AccessTokenResultStatus>(testJsRuntime.GetAccessTokenResult.Status, ignoreCase: true));
        Assert.Equal(expectedRedirectUrl, result.RedirectUrl);
        Assert.Equal(tokenOptions, (AccessTokenRequestOptions)testJsRuntime.PastInvocations[^ 1].args[0]);
Exemple #6
0
    /// <inheritdoc />
    public virtual async ValueTask <AccessTokenResult> RequestAccessToken(AccessTokenRequestOptions options)
    {
        if (options is null)
        {
            throw new ArgumentNullException(nameof(options));
        }

        await EnsureAuthService();

        var result = await JsRuntime.InvokeAsync <InternalAccessTokenResult>("AuthenticationService.getAccessToken", options);

        if (!Enum.TryParse <AccessTokenResultStatus>(result.Status, ignoreCase: true, out var parsedStatus))
        {
            throw new InvalidOperationException($"Invalid access token result status '{result.Status ?? "(null)"}'");
        }

        if (parsedStatus == AccessTokenResultStatus.RequiresRedirect)
        {
            var redirectUrl = GetRedirectUrl(options.ReturnUrl);
            result.RedirectUrl = redirectUrl.ToString();
        }

        return(new AccessTokenResult(parsedStatus, result.Token, result.RedirectUrl));
    }
Exemple #7
0
 public ValueTask <AccessTokenResult> RequestAccessToken(AccessTokenRequestOptions options)
 {
     throw new NotImplementedException();
 }
 public ValueTask <AccessTokenResult> RequestAccessToken(AccessTokenRequestOptions options)
 {
     return(this.RequestAccessToken());
 }