Esempio n. 1
0
        private async Task HandleApiToken(AuthorizationCodeReceivedContext context)
        {
            if (!context.HandledCodeRedemption)
            {
                string                      userId                = context.Principal.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier");
                IDistributedCache           distributedCache      = context.HttpContext.RequestServices.GetService <IDistributedCache>();
                DistributedMemoryTokenCache tokenCache            = new DistributedMemoryTokenCache(userId, distributedCache);
                string                      authority             = context.Options.Authority;
                string                      code                  = context.TokenEndpointRequest.Code;
                string                      resource              = context.Options.Resource;
                string                      clientId              = context.Options.ClientId;
                string                      clientSecret          = context.Options.ClientSecret;
                string                      redirectUri           = context.TokenEndpointRequest.RedirectUri;
                AuthenticationContext       authenticationContext = new AuthenticationContext(authority, true, tokenCache);
                var result = await authenticationContext.AcquireTokenByAuthorizationCodeAsync(code, new Uri(redirectUri), new ClientCredential(clientId, clientSecret), resource);

                context.HandleCodeRedemption(result.AccessToken, result.IdToken);
            }
        }
Esempio n. 2
0
        private async Task <string> GetAccessToken()
        {
            try
            {
                string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
                DistributedMemoryTokenCache distributedMemoryTokenCache = new DistributedMemoryTokenCache(userObjectID, _distributedCache);
                AuthenticationContext       authenticationContext       = new AuthenticationContext(
                    $"{_options.Value.Instance}{_options.Value.TenantId}", distributedMemoryTokenCache
                    );

                var result = await authenticationContext
                             .AcquireTokenSilentAsync(
                    _options.Value.Resource,
                    new ClientCredential(_options.Value.ClientId, _options.Value.ClientSecret),
                    new UserIdentifier(userObjectID, UserIdentifierType.UniqueId)
                    );

                return(result.AccessToken);
            }
            catch (Exception ex)
            {
                return("401");
            }
        }