/// <summary>
        /// acquires a <see cref="TokenPair"/> from the authority via an interactive user logon
        /// prompt.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator of the resource access tokens are being requested for.
        /// </param>
        /// <param name="clientId">Identifier of the client requesting the token.</param>
        /// <param name="resource">
        /// Identifier of the target resource that is the recipient of the requested token.
        /// </param>
        /// <param name="redirectUri">
        /// Address to return to upon receiving a response from the authority.
        /// </param>
        /// <param name="queryParameters">
        /// Optional: appended as-is to the query string in the HTTP authentication request to the
        /// authority.
        /// </param>
        /// <returns>If successful a <see cref="TokenPair"/>; otherwise <see langword="null"/>.</returns>
        public TokenPair AcquireToken(TargetUri targetUri, string clientId, string resource, Uri redirectUri, string queryParameters = null)
        {
            Debug.Assert(targetUri != null && targetUri.IsAbsoluteUri, "The targetUri parameter is null");
            Debug.Assert(!String.IsNullOrWhiteSpace(clientId), "The clientId parameter is null or empty");
            Debug.Assert(!String.IsNullOrWhiteSpace(resource), "The resource parameter is null or empty");
            Debug.Assert(redirectUri != null, "The redirectUri parameter is null");
            Debug.Assert(redirectUri.IsAbsoluteUri, "The redirectUri parameter is not an absolute Uri");

            Trace.WriteLine("AzureAuthority::AcquireToken");

            TokenPair tokens = null;

            queryParameters = queryParameters ?? String.Empty;

            try
            {
                Trace.WriteLine(String.Format("   authority host url = '{0}'.", AuthorityHostUrl));

                AuthenticationContext authCtx    = new AuthenticationContext(AuthorityHostUrl, _adalTokenCache);
                AuthenticationResult  authResult = authCtx.AcquireToken(resource, clientId, redirectUri, PromptBehavior.Always, UserIdentifier.AnyUser, queryParameters);
                tokens = new TokenPair(authResult);

                Trace.WriteLine("   token acquisition succeeded.");
            }
            catch (AdalException)
            {
                Trace.WriteLine("   token acquisition failed.");
            }

            return(tokens);
        }
        /// <summary>
        /// acquires a <see cref="TokenPair"/> from the authority using optionally provided
        /// credentials or via the current identity.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator of the resource access tokens are being requested for.
        /// </param>
        /// <param name="clientId">Identifier of the client requesting the token.</param>
        /// <param name="resource">
        /// Identifier of the target resource that is the recipient of the requested token.
        /// </param>
        /// <param name="credentials">Optional: user credential to use for token acquisition.</param>
        /// <returns>If successful a <see cref="TokenPair"/>; otherwise <see langword="null"/>.</returns>
        public async Task <TokenPair> AcquireTokenAsync(TargetUri targetUri, string clientId, string resource, Credential credentials = null)
        {
            Debug.Assert(targetUri != null && targetUri.IsAbsoluteUri, "The targetUri parameter is null or invalid");
            Debug.Assert(!String.IsNullOrWhiteSpace(clientId), "The clientId parameter is null or empty");
            Debug.Assert(!String.IsNullOrWhiteSpace(resource), "The resource parameter is null or empty");

            Trace.WriteLine("AzureAuthority::AcquireTokenAsync");

            TokenPair tokens = null;

            try
            {
                Trace.WriteLine(String.Format("   authority host url = '{0}'.", AuthorityHostUrl));

                UserCredential        userCredential = credentials == null ? new UserCredential() : new UserCredential(credentials.Username, credentials.Password);
                AuthenticationContext authCtx        = new AuthenticationContext(AuthorityHostUrl, _adalTokenCache);
                AuthenticationResult  authResult     = await authCtx.AcquireTokenAsync(resource, clientId, userCredential);

                tokens = new TokenPair(authResult);

                Trace.WriteLine("   token acquisition succeeded.");
            }
            catch (AdalException)
            {
                Trace.WriteLine("   token acquisition failed.");
            }

            return(tokens);
        }
예제 #3
0
        /// <summary>
        /// Attempts to generate a new personal access token (credentials) via use of a stored
        /// Azure refresh token, identified by the target resource.
        /// </summary>
        /// <param name="targetUri">The 'key' by which to identify the refresh token.</param>
        /// <param name="requireCompactToken">Generates a compact token if <see langword="true"/>;
        /// generates a self describing token if <see langword="false"/>.</param>
        /// <returns><see langword="true"/> if successful; <see langword="false"/> otherwise.</returns>
        public async Task <bool> RefreshCredentials(TargetUri targetUri, bool requireCompactToken)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);

            Trace.WriteLine("BaseVstsAuthentication::RefreshCredentials");

            try
            {
                TokenPair tokens = null;

                Token refreshToken = null;
                // attempt to read from the local store
                if (this.AdaRefreshTokenStore.ReadToken(targetUri, out refreshToken))
                {
                    if ((tokens = await this.VstsAuthority.AcquireTokenByRefreshTokenAsync(targetUri, this.ClientId, this.Resource, refreshToken)) != null)
                    {
                        Trace.WriteLine("   Azure token found in primary cache.");

                        this.TenantId = tokens.AccessToken.TargetIdentity;

                        return(await this.GeneratePersonalAccessToken(targetUri, tokens.AccessToken, requireCompactToken));
                    }
                }

                Token federatedAuthToken;
                // attempt to utilize any fedauth tokens captured by the IDE
                if (this.VstsIdeTokenCache.ReadToken(targetUri, out federatedAuthToken))
                {
                    Trace.WriteLine("   federated auth token found in IDE cache.");

                    return(await this.GeneratePersonalAccessToken(targetUri, federatedAuthToken, requireCompactToken));
                }
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);
            }

            Trace.WriteLine("   failed to refresh credentials.");
            return(false);
        }
        /// <summary>
        /// Acquires an access token from the authority using a previously acquired refresh token.
        /// </summary>
        /// <param name="targetUri">
        /// The uniform resource indicator of the resource access tokens are being requested for.
        /// </param>
        /// <param name="clientId">Identifier of the client requesting the token.</param>
        /// <param name="resource">
        /// Identifier of the target resource that is the recipient of the requested token.
        /// </param>
        /// <param name="refreshToken">The <see cref="Token"/> of type <see cref="TokenType.Refresh"/>
        /// to be used to acquire the access token.</param>
        /// <returns>If successful a <see cref="TokenPair"/>; otherwise <see langword="null"/>.</returns>
        public async Task <TokenPair> AcquireTokenByRefreshTokenAsync(TargetUri targetUri, string clientId, string resource, Token refreshToken)
        {
            Debug.Assert(targetUri != null && targetUri.IsAbsoluteUri, "The targetUri parameter is null or invalid");
            Debug.Assert(!String.IsNullOrWhiteSpace(clientId), "The clientId parameter is null or empty");
            Debug.Assert(!String.IsNullOrWhiteSpace(resource), "The resource parameter is null or empty");
            Debug.Assert(refreshToken != null, "The refreshToken parameter is null");
            Debug.Assert(refreshToken.Type == TokenType.Refresh, "The value of refreshToken parameter is not a refresh token");
            Debug.Assert(!String.IsNullOrWhiteSpace(refreshToken.Value), "The value of refreshToken parameter is null or empty");

            TokenPair tokens = null;

            try
            {
                string authorityHostUrl = AuthorityHostUrl;

                if (refreshToken.TargetIdentity != Guid.Empty)
                {
                    authorityHostUrl = GetAuthorityUrl(refreshToken.TargetIdentity);

                    Trace.WriteLine("   authority host url set by refresh token.");
                }

                Trace.WriteLine(String.Format("   authority host url = '{0}'.", authorityHostUrl));

                AuthenticationContext authCtx    = new AuthenticationContext(authorityHostUrl, _adalTokenCache);
                AuthenticationResult  authResult = await authCtx.AcquireTokenByRefreshTokenAsync(refreshToken.Value, clientId, resource);

                tokens = new TokenPair(authResult);

                Trace.WriteLine("   token acquisition succeeded.");
            }
            catch (AdalException)
            {
                Trace.WriteLine("   token acquisition failed.");
            }

            return(tokens);
        }