Beispiel #1
0
        /// <summary>
        /// Checks that an access token is available.
        /// </summary>
        /// <returns>The access token.</returns>
        internal static async Task <string> EnsureAccessTokenAvailableAsync(string serviceResourceId)
        {
            try
            {
                // First, look for the authority used during the last authentication.
                // If that value is not populated, use _commonAuthority.
                string authority = null;
                if (String.IsNullOrEmpty(_lastAuthority))
                {
                    authority = _commonAuthority;
                }
                else
                {
                    authority = _lastAuthority;
                }

                // Create an AuthenticationContext using this authority.
                _authenticationContext = new AuthenticationContext(authority);

                // Set the value of _authenticationContext.UseCorporateNetwork to true so that you
                // can use this app inside a corporate intranet. If the value of UseCorporateNetwork
                // is true, you also need to add the Enterprise Authentication, Private Networks, and
                // Shared User Certificates capabilities in the Package.appxmanifest file.
                //_authenticationContext.UseCorporateNetwork = true;

                //Get the current app object, which exposes the ClientId and ReturnUri properties
                // that we need in the following call to AcquireTokenAsync
                App currentApp = (App)App.Current;

                AuthenticationResult authenticationResult;

                // An attempt is first made to acquire the token silently.
                // If that fails, then we try to acquire the token by prompting the user.
                authenticationResult = await _authenticationContext.AcquireTokenSilentAsync(serviceResourceId, currentApp.ClientId);

                if (authenticationResult.Status != AuthenticationStatus.Success)
                {
                    // Try to authenticate by prompting the user
                    authenticationResult = await _authenticationContext.AcquireTokenAsync(serviceResourceId, currentApp.ClientId, currentApp.ReturnUri);

                    // Check the result of the authentication operation
                    if (authenticationResult.Status != AuthenticationStatus.Success)
                    {
                        // Something went wrong, probably the user cancelled the sign in process
                        return(null);
                    }
                }

                // Store relevant info about user and resource
                _loggedInUser = authenticationResult.UserInfo.UniqueId;
                // The new last authority is in the form https://login.windows.net/{TenantId}
                _lastAuthority    = App.Current.Resources["ida:AuthorizationUri"].ToString() + "/" + authenticationResult.TenantId;
                UserAccount       = authenticationResult.UserInfo.DisplayableId;
                ServiceResourceId = serviceResourceId;

                // If the acccess token has changed
                if (!String.Equals(_accessToken, authenticationResult.AccessToken))
                {
                    // Raise an event to let other components know that the token has changed,
                    // so they can react accordingly (for example, updating the data source)
                    AccessTokenChanged(null, EventArgs.Empty);
                    // and store the new acces token
                    _accessToken = authenticationResult.AccessToken;
                }

                return(_accessToken);
            }
            // The following is a list of all exceptions you should consider handling in your app.
            // In the case of this sample, the exceptions are handled by returning null upstream.
            catch (MissingConfigurationValueException mcve)
            {
                MessageDialogHelper.DisplayException(mcve);

                // Connected services not added correctly, or permissions not set correctly.
                _authenticationContext.TokenCache.Clear();
                return(null);
            }
            catch (AuthenticationFailedException afe)
            {
                MessageDialogHelper.DisplayException(afe);

                // Failed to authenticate the user
                _authenticationContext.TokenCache.Clear();
                return(null);
            }
            catch (ArgumentException ae)
            {
                MessageDialogHelper.DisplayException(ae as Exception);

                // Argument exception
                _authenticationContext.TokenCache.Clear();
                return(null);
            }
        }