Пример #1
0
        // Gets a token by Authorization Code.
        // Using password (secret) to authenticate. Production apps should use a certificate.
        public async Task <AuthenticationResult> GetTokenByAuthorizationCodeAsync(string userId, string code, string redirectHost)
        {
            TokenCache userTokenCache = new SessionCacheService(userId, _memoryCache).GetCacheInstance();

            if (!_aadInstance.Last().Equals('/')) // TODO: extract and DRY
            {
                _aadInstance = _aadInstance + "/";
            }

            _aadInstance = _aadInstance + _tenantId;

            try
            {
                AuthenticationContext authContext = new AuthenticationContext(_aadInstance, userTokenCache);
                ClientCredential      credential  = new ClientCredential(_appId, _appSecret);
                AuthenticationResult  result      = await authContext.AcquireTokenByAuthorizationCodeAsync(
                    code,
                    new Uri(redirectHost + _redirectUri),
                    credential,
                    _graphResourceId);

                return(result);
            }
            catch (Exception ex)
            {
                // In most cases the Client Secret provided would be invalid. Update it in the secret store.
                _telemetryService.TrackException(ex);
                return(null);
            }
        }
        public async Task <string> GetGraphAccessTokenAsync(string userId, string _aadInstance, string _appId, string _appSecret, string _tenantId, IMemoryCache _memoryCache, string _graphResourceId)
        {
            TokenCache userTokenCache = new SessionCacheService(userId, _memoryCache).GetCacheInstance();

            // TODO: extract and DRY
            if (!_aadInstance.Last().Equals('/'))
            {
                _aadInstance = _aadInstance + "/";
            }

            _aadInstance = _aadInstance + _tenantId;
            try
            {
                AuthenticationContext authContext = new AuthenticationContext(_aadInstance, userTokenCache);
                ClientCredential      credential  = new ClientCredential(_appId, _appSecret);
                AuthenticationResult  result      = await authContext.AcquireTokenSilentAsync(
                    _graphResourceId,
                    credential,
                    new UserIdentifier(userId, UserIdentifierType.UniqueId));

                return(result.AccessToken);
            }
            catch (Exception ex)
            {
                // TODO: log ex
                return(null);
            }
        }