private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.AccessToken.Text = string.Empty;
            this.context          = await AuthenticationContext.CreateAsync(sts.Authority);

            this.context.TokenCache.Clear();
        }
 private async Task InitializeAuthentication()
 {
     if (authContext == null || authContext.Authority != OAuthUrl)
     {
         authContext = await AuthenticationContext.CreateAsync(OAuthUrl);
     }
 }
Ejemplo n.º 3
0
        public async Task MsAppRedirectUriTest()
        {
            Sts sts = new AadSts();
            AuthenticationContext context = await AuthenticationContext.CreateAsync(sts.Authority);

            try
            {
                UserIdentifierType t = UserIdentifierType.RequiredDisplayableId;
                context.AcquireTokenAndContinue(sts.ValidResource, sts.ValidClientId, new Uri("ms-app://test/"), null);

                Verify.Fail("Argument exception expected");
            }
            catch (AdalException ex)
            {
                Verify.AreEqual(ex.ErrorCode, Sts.AuthenticationUiFailedError);
                Verify.IsTrue(ex.InnerException is ArgumentException);
            }

            try
            {
                WebAuthenticationBroker.GetCurrentApplicationCallbackUri();

                Verify.Fail("Exception expected");
            }
            catch (Exception ex)
            {
                Verify.IsTrue(ex.Message.Contains("hostname"));
            }

            try
            {
                context.AcquireTokenAndContinue(sts.ValidResource, sts.ValidClientId, null, null);

                Verify.Fail("Exception expected");
            }
            catch (AdalException ex)
            {
                Verify.AreEqual(ex.ErrorCode, "need_to_set_callback_uri_as_local_setting");
            }

            try
            {
                // Incorrect ms-app
                ApplicationData.Current.LocalSettings.Values["CurrentApplicationCallbackUri"] = "ms-app://s-1-15-2-2097830667-3131301884-2920402518-3338703368-1480782779-4157212157-3811015497/";
                context.AcquireTokenAndContinue(sts.ValidResource, sts.ValidClientId, null, null);

                Verify.Fail("Exception expected");
            }
            catch (AdalException ex)
            {
                Verify.AreEqual(ex.ErrorCode, Sts.AuthenticationUiFailedError);
            }
        }
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            this.AccessToken.Text = string.Empty;

            this.context = await AuthenticationContext.CreateAsync(sts.Authority);

            var result = await this.context.AcquireTokenSilentAsync(sts.ValidResource, sts.ValidClientId, sts.ValidUserId);

            if (result.Status == AuthenticationStatus.Success)
            {
                this.DisplayToken(result);
            }
            else
            {
                this.context.AcquireTokenAndContinue(sts.ValidResource, sts.ValidClientId, sts.ValidDefaultRedirectUri, sts.ValidUserId, this.DisplayToken);
            }
        }
Ejemplo n.º 5
0
        //Phone Authentication methods
#if WINDOWS_PHONE_APP
        public async static Task <AuthenticationResult> AuthenticateSilently()
        {
            //First, look for the authority used during the last authentication.
            //If that value is not populated, return null, because this means that the
            //last user disconnected.
            if (String.IsNullOrEmpty(LastAuthority))
            {
                return(null);
            }
            else
            {
                _authenticationContext = await AuthenticationContext.CreateAsync(LastAuthority);

                AuthenticationResult result = await _authenticationContext.AcquireTokenSilentAsync(DiscoveryResourceId, ClientID);

                return(result);
            }
        }
Ejemplo n.º 6
0
        public static async void BeginAuthentication()
        {
            //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;
            }

            _authenticationContext = await AuthenticationContext.CreateAsync(authority);

            _authenticationContext.AcquireTokenAndContinue(DiscoveryResourceId, ClientID, _returnUri, null);
        }
        public MainPage()
        {
            this.InitializeComponent();

            this.NavigationCacheMode = NavigationCacheMode.Required;

            //
            // Every Windows Store application has a unique URI.
            // Windows ensures that only this application will receive messages sent to this URI.
            // ADAL uses this URI as the application's redirect URI to receive OAuth responses.
            //
            // To determine this application's redirect URI, which is necessary when registering the app
            //      in AAD, set a breakpoint on the next line, run the app, and copy the string value of the URI.
            //      This is the only purposes of this line of code, it has no functional purpose in the application.
            //
            redirectURI = Windows.Security.Authentication.Web.WebAuthenticationBroker.GetCurrentApplicationCallbackUri();

            // ADAL for Windows Phone 8.1 builds AuthenticationContext instances throuhg a factory, which performs authority validation at creation time
            authContext = AuthenticationContext.CreateAsync(authority).GetResults();
        }
Ejemplo n.º 8
0
        public static async System.Threading.Tasks.Task GetTokenSilent()
        {
            if (String.IsNullOrEmpty(CRMHelper.AuthorityUrl))
            {
                await CRMHelper.DiscoveryAuthority();
            }

            // If authContext is null, then generate it.
            if (authContext == null)
#if WINDOWS_PHONE_APP
            {   // ADAL for Windows Phone 8.1 builds AuthenticationContext instances throuhg a factory, which performs authority validation at creation time
                authContext = AuthenticationContext.CreateAsync(CRMHelper.AuthorityUrl).GetResults();
            }
            AuthenticationResult result = await authContext.AcquireTokenSilentAsync(CRMHelper.ResourceName, CRMHelper.ClientId);
#else
            { authContext = new AuthenticationContext(CRMHelper.AuthorityUrl, false); }
            AuthenticationResult result = await authContext.AcquireTokenAsync(CRMHelper.ResourceName, CRMHelper.ClientId);
#endif

            if (result != null && result.Status == AuthenticationStatus.Success)
            {
                // A token was successfully retrieved. Then store it.
                StoreToken(result);
            }
            else
            {
#if WINDOWS_PHONE_APP
                // Clear the AccessToken first so that any Service Calls waits until it's filled.
                proxy.AccessToken = "";
                // In case credential was wrong, clear the token cache first.
                authContext.TokenCache.Clear();
                // Acquiring a token without user interaction was not possible.
                // Trigger an authentication experience and specify that once a token has been obtained the StoreToken method should be called.
                authContext.AcquireTokenAndContinue(CRMHelper.ResourceName, CRMHelper.ClientId, new Uri(CRMHelper.RedirectUri), StoreToken);
#else
                DisplayErrorWhenAcquireTokenFails(result);
#endif
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Gets a valid authentication token. Also refreshes the access token if it has expired.
        /// </summary>
        /// <remarks>
        /// Used by the API request generators before making calls to the OneNote APIs.
        /// </remarks>
        /// <returns>valid authentication token</returns>
        internal static async Task <AuthenticationResult> GetAuthenticationResult()
        {
            if (String.IsNullOrEmpty(AccessToken))
            {
                try
                {
                    //look to see if we have an authentication context in cache already
                    //we would have gotten this when we authenticated previously
                    var allCachedItems   = AuthContext.TokenCache.ReadItems();
                    var validCachedItems = allCachedItems
                                           .Where(i => i.ExpiresOn > DateTimeOffset.UtcNow.UtcDateTime && IsO365Token(i.IdentityProvider))
                                           .OrderByDescending(e => e.ExpiresOn);
                    var cachedItem = validCachedItems.First();
                    if (cachedItem != null)
                    {
                        //re-bind AuthenticationContext to the authority source of the cached token.
                        //this is needed for the cache to work when asking for a token from that authority.
#if WINDOWS_PHONE_APP
                        AuthContext = AuthenticationContext.CreateAsync(cachedItem.Authority, true).GetResults();
#else
                        AuthContext = new AuthenticationContext(cachedItem.Authority, true);
#endif

                        //try to get the AccessToken silently using the resourceId that was passed in
                        //and the client ID of the application.
                        _authenticationResult = await AuthContext.AcquireTokenSilentAsync(GetResourceHost(ResourceUri), ClientId);

                        RefreshAuthTokenIfNeeded().Wait();
                    }
                }
                catch (Exception)
                {
                    //not in cache; we'll get it with the full oauth flow
                }
            }

            if (string.IsNullOrEmpty(AccessToken))
            {
                try
                {
                    AuthContext.TokenCache.Clear();
#if WINDOWS_PHONE_APP
                    _authenticationResult = await AuthContext.AcquireTokenSilentAsync(GetResourceHost(ResourceUri), ClientId);

                    if (_authenticationResult == null || string.IsNullOrEmpty(_authenticationResult.AccessToken))
                    {
                        AuthContext.AcquireTokenAndContinue(GetResourceHost(ResourceUri), ClientId, new Uri(RedirectUri), null);
                    }
#else
                    _authenticationResult =
                        await AuthContext.AcquireTokenAsync(GetResourceHost(ResourceUri), ClientId, new Uri(RedirectUri));
#endif
                }
                catch (Exception)
                {
                    // Authentication failed
                    if (Debugger.IsAttached)
                    {
                        Debugger.Break();
                    }
                }
            }

            return(_authenticationResult);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Checks that an OutlookServicesClient object is available.
        /// </summary>
        /// <returns>The OutlookServicesClient object. </returns>
        public static async Task <OutlookServicesClient> GetOutlookClientAsync(string capability)
        {
            if (_outlookClient != null)
            {
                return(_outlookClient);
            }
            else
            {
                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.
#if WINDOWS_APP
                    _authenticationContext = new AuthenticationContext(authority);
#endif
#if WINDOWS_PHONE_APP
                    _authenticationContext = await AuthenticationContext.CreateAsync(authority);
#endif

#if WINDOWS_APP
                    // 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;
#endif

                    //See the Discovery Service Sample (https://github.com/OfficeDev/Office365-Discovery-Service-Sample)
                    //for an approach that improves performance by storing the discovery service information in a cache.
                    DiscoveryClient discoveryClient = new DiscoveryClient(
                        async() => await GetTokenHelperAsync(_authenticationContext, DiscoveryResourceId));

                    // Get the specified capability ("Mail").
                    CapabilityDiscoveryResult result =
                        await discoveryClient.DiscoverCapabilityAsync(capability);

                    var token = await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId);

                    // Check the token
                    if (String.IsNullOrEmpty(token))
                    {
                        // User cancelled sign-in
                        return(null);
                    }
                    else
                    {
                        _outlookClient = new OutlookServicesClient(
                            result.ServiceEndpointUri,
                            async() => await GetTokenHelperAsync(_authenticationContext, result.ServiceResourceId));

                        return(_outlookClient);
                    }
                }
                // 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 (DiscoveryFailedException dfe)
                {
                    // Discovery failed.
                    Debug.WriteLine("Exception: " + dfe.Message);
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
                catch (ArgumentException ae)
                {
                    // Argument exception
                    Debug.WriteLine("Exception: " + ae.Message);
                    _authenticationContext.TokenCache.Clear();
                    return(null);
                }
            }
        }
        /// <summary>
        /// This method try to obtain AccessToken by using OAuth2 authentication agianst Microsoft Azure AD.
        /// </summary>
        static public async Task GetTokenSilent()
        {
            // Before create AuthenticationContext, check if Authority(OAuthUrl) is available.
            if (String.IsNullOrEmpty(CRMHelper.OAuthUrl))
            {
                bool success = true;
                try
                {
                    await CRMHelper.DiscoveryAuthority();
                }
                catch (Exception ex)
                {
                    // If failed to retireve OAuthUrl, then make success as false
                    success = false;
                }

                // If failed to retrieve OAuthUrl, chances are user mistype ServerUrl.
                if (!success)
                {
                    MessageDialog dialog = new MessageDialog("OAuth Url retrieve failed. Please check Service URL again.");
                    await dialog.ShowAsync();

                    return;
                }
            }

            if (CRMHelper.SignOut)
            {
                if (authContext != null)
                {
                    authContext.TokenCache.Clear();
                }
                CRMHelper.SignOut = false;
            }

            // Create AuthenticationContext by using OAuthUrl.
            if (authContext == null)
            {
                authContext = await AuthenticationContext.CreateAsync(CRMHelper.OAuthUrl);
            }

            // Try to acquire token without prompting user first.
            AuthenticationResult result = await authContext.AcquireTokenSilentAsync(CRMHelper.ResourceName, CRMHelper.ClientId);

            // Check the result.
            if (result != null && result.Status == AuthenticationStatus.Success)
            {
                // A token was successfully retrieved. Then store it.
                StoreToken(result);
            }
            // If failed to obtain token without prompting, then prompt user for credentials
            else
            {
                // Clear AccessToken
                CRMHelper._proxy.AccessToken = "";
                // In case credential was wrong, clear the token cache first.
                authContext.TokenCache.Clear();
                // Acquiring a token without user interaction was not possible.
                // Trigger an authentication experience and specify that once a token has been obtained the StoreToken method should be called.
                authContext.AcquireTokenAndContinue(CRMHelper.ResourceName, CRMHelper.ClientId, new Uri(CRMHelper.RedirectUri), StoreToken);
            }
        }
Ejemplo n.º 12
0
 private static async Task <AuthenticationContext> CreateAsync(string authority, bool validateAuthority, TokenCache tokenCache, Guid correlationId)
 {
     return(await AuthenticationContext.CreateAsync(authority, validateAuthority, tokenCache, correlationId));
 }
Ejemplo n.º 13
0
 private static async Task <AuthenticationContext> CreateAsync(string authority, bool validateAuthority)
 {
     return(await AuthenticationContext.CreateAsync(authority, validateAuthority));
 }