public override async Task <AppAuthenticationResult> GetAuthResultAsync(string resource, string authority,
                                                                                CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                // Validate resource, since it gets sent as a command line argument to Azure CLI
                ValidationHelper.ValidateResource(resource);

                // Execute Azure CLI to get token
                string response = await _processManager.ExecuteAsync(new Process { StartInfo = GetProcessStartInfo(resource) }, cancellationToken).ConfigureAwait(false);

                // Parse the response
                TokenResponse tokenResponse = TokenResponse.Parse(response);

                var accessToken = tokenResponse.AccessToken2;

                AccessToken token = AccessToken.Parse(accessToken);

                PrincipalUsed.IsAuthenticated = true;

                if (token != null)
                {
                    // Set principal used based on the claims in the access token.
                    PrincipalUsed.UserPrincipalName = !string.IsNullOrEmpty(token.Upn) ? token.Upn : token.Email;
                    PrincipalUsed.TenantId          = token.TenantId;
                }

                return(AppAuthenticationResult.Create(tokenResponse));
            }
            catch (Exception exp)
            {
                throw new AzureServiceTokenProviderException(ConnectionString, resource, authority,
                                                             $"{AzureServiceTokenProviderException.AzureCliUsed} {AzureServiceTokenProviderException.GenericErrorMessage} {exp.Message}");
            }
        }
        public async Task <AuthenticationToken> GetAuthResultAsync(string resource, string authority)
        {
            try
            {
                // Validate resource, since it gets sent as a command line argument to Azure CLI
                ValidationHelper.ValidateResource(resource);

                // Execute Azure CLI to get token
                var response = await _processManager.ExecuteAsync(new Process { StartInfo = GetProcessStartInfo(resource) }).ConfigureAwait(false);

                // Parse the response
                var tokenResponse = TokenResponse.Parse(response);

                var accessToken = tokenResponse.AccessToken2;

                var token = AccessToken.Parse(accessToken);

                PrincipalUsed.IsAuthenticated = true;

                if (token != null)
                {
                    // Set principal used based on the claims in the access token.
                    PrincipalUsed.UserPrincipalName = !string.IsNullOrEmpty(token.Upn) ? token.Upn : token.Email;
                    PrincipalUsed.TenantId          = token.TenantId;
                }

                var authResult = Models.AppAuthenticationResult.Create(tokenResponse, TokenResponse.DateFormat.DateTimeString);

                var authenticationToken = new AuthenticationToken
                {
                    AccessToken  = authResult.AccessToken,
                    TokenType    = authResult.TokenType,
                    Resource     = authResult.Resource,
                    ExpiresOn    = tokenResponse.ExpiresOn,
                    ExpiresIn    = token.ExpiryTime.ToString(),
                    ExtExpiresIn = token.ExpiryTime.ToString(),
                    RefreshToken = tokenResponse.AccessToken2
                };

                return(authenticationToken);
            }
            catch (Exception exp)
            {
                throw new Exception(
                          $"{nameof(AzureCliAccessTokenProvider)} not able to obtain the token for {ConnectionString} , {resource} , {authority}, {exp.Message}");
            }
        }
        public override async Task <AppAuthenticationResult> GetAuthResultAsync(string resource, string authority,
                                                                                CancellationToken cancellationToken = default(CancellationToken))
        {
            try
            {
                // Validate resource, since it gets sent as a command line argument to Visual Studio token provider.
                ValidationHelper.ValidateResource(resource);

                _visualStudioTokenProviderFile = _visualStudioTokenProviderFile ?? GetTokenProviderFile();

                // Get process start infos based on Visual Studio token providers
                var processStartInfos = GetProcessStartInfos(_visualStudioTokenProviderFile, resource, UriHelper.GetTenantByAuthority(authority));

                // To hold reason why token could not be acquired per token provider tried.
                Dictionary <string, string> exceptionDictionary = new Dictionary <string, string>();

                foreach (var startInfo in processStartInfos)
                {
                    try
                    {
                        // For each of them, try to get token
                        string response = await _processManager
                                          .ExecuteAsync(new Process { StartInfo = startInfo }, cancellationToken)
                                          .ConfigureAwait(false);

                        TokenResponse tokenResponse = TokenResponse.Parse(response);

                        AccessToken token = AccessToken.Parse(tokenResponse.AccessToken);

                        PrincipalUsed.IsAuthenticated = true;

                        if (token != null)
                        {
                            // Set principal used based on the claims in the access token.
                            PrincipalUsed.UserPrincipalName =
                                !string.IsNullOrEmpty(token.Upn) ? token.Upn : token.Email;

                            PrincipalUsed.TenantId = token.TenantId;
                        }

                        return(AppAuthenticationResult.Create(tokenResponse));
                    }
                    catch (Exception exp)
                    {
                        // If token cannot be acquired using a token provider, try the next one
                        exceptionDictionary[Path.GetFileName(startInfo.FileName)] = exp.Message;
                    }
                }

                // Could not acquire access token, throw exception
                string message = string.Empty;

                // Include exception details for each token provider that was tried
                foreach (string key in exceptionDictionary.Keys)
                {
                    message += Environment.NewLine +
                               $"Exception for Visual Studio token provider {key} : {exceptionDictionary[key]} ";
                }

                // Throw exception if none of the token providers worked
                throw new Exception(message);
            }
            catch (Exception exp)
            {
                throw new AzureServiceTokenProviderException(ConnectionString, resource, authority,
                                                             $"{AzureServiceTokenProviderException.VisualStudioUsed} {AzureServiceTokenProviderException.GenericErrorMessage} {exp.Message}");
            }
        }
Esempio n. 4
0
        public async Task <AuthenticationToken> GetAuthResultAsync(string resource, string authority)
        {
            try
            {
                // Validate resource, since it gets sent as a command line argument to Visual Studio token provider.
                ValidationHelper.ValidateResource(resource);

                _visualStudioTokenProviderFile = _visualStudioTokenProviderFile ?? GetTokenProviderFile();

                // Get process start infos based on Visual Studio token providers
                var processStartInfos = GetProcessStartInfos(_visualStudioTokenProviderFile, resource, UriHelper.GetTenantByAuthority(authority));

                // To hold reason why token could not be acquired per token provider tried.
                var exceptionDictionary = new Dictionary <string, string>();

                foreach (var startInfo in processStartInfos)
                {
                    try
                    {
                        // For each of them, try to get token
                        var response = await _processManager
                                       .ExecuteAsync(new Process { StartInfo = startInfo })
                                       .ConfigureAwait(false);

                        var tokenResponse = TokenResponse.Parse(response);

                        var accessToken = AccessToken.Parse(tokenResponse.AccessToken);

                        PrincipalUsed.IsAuthenticated = true;

                        if (accessToken != null)
                        {
                            // Set principal used based on the claims in the access token.
                            PrincipalUsed.UserPrincipalName =
                                !string.IsNullOrEmpty(accessToken.Upn) ? accessToken.Upn : accessToken.Email;

                            PrincipalUsed.TenantId = accessToken.TenantId;
                        }

                        var authResult = Models.AppAuthenticationResult.Create(tokenResponse, TokenResponse.DateFormat.DateTimeString);

                        var authenticationToken = new AuthenticationToken
                        {
                            AccessToken  = authResult.AccessToken,
                            TokenType    = authResult.TokenType,
                            Resource     = authResult.Resource,
                            ExpiresOn    = tokenResponse.ExpiresOn,
                            ExpiresIn    = accessToken.ExpiryTime.ToString(),
                            ExtExpiresIn = accessToken.ExpiryTime.ToString(),
                            RefreshToken = tokenResponse.AccessToken,
                        };

                        return(authenticationToken);
                    }
                    catch (Exception exp)
                    {
                        // If token cannot be acquired using a token provider, try the next one
                        exceptionDictionary[Path.GetFileName(startInfo.FileName)] = exp.Message;
                    }
                }

                // Could not acquire access token, throw exception
                var message = string.Empty;

                // Include exception details for each token provider that was tried
                foreach (var key in exceptionDictionary.Keys)
                {
                    message += Environment.NewLine +
                               $"Exception for Visual Studio token provider {key} : {exceptionDictionary[key]} ";
                }

                // Throw exception if none of the token providers worked
                throw new Exception(message);
            }
            catch (Exception exp)
            {
                throw new Exception(
                          $"{nameof(VisualStudioAccessTokenProvider)} not able to obtain the token for {ConnectionString} , {resource} , {authority}, {exp.Message}");
            }
        }