Showing posts with label Windows UWP. Show all posts
Showing posts with label Windows UWP. Show all posts

Thursday, 25 August 2016

Authenticate windows 10 app with Azure AD (WAM)

Technology: Windows 10 Apps, Azure AD, WAM

Required Name Spaces:

using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.Security.Authentication.Web;
using Windows.Security.Authentication.Web.Core;
using Windows.Security.Credentials;



        
        public static string AdalClientId = App.clintID; //clientID from Azure AD
        public static string AdalResourceId = App.ServiceResourceUrl; // Web api Service appID from Azure AD
        const string MicrosoftAccountProviderId = "https://login.microsoft.com";
        public string AdalIssuerAuthority = "https://login.windows.net/contoso.onmicrosoft.com";
        
        string URI = string.Format("ms-appx-web://Microsoft.AAD.BrokerPlugIn/{0}", WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); //URI need to enter while registering into Azure AD
        string szReturnUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri;
        AuthenticationResult AResult;
        public async Task<string> Authenticate(bool prompt)
        {
            WebAccountProvider provider = await WebAuthenticationCoreManager.FindAccountProviderAsync(MicrosoftAccountProviderId, AdalIssuerAuthority);

            try
            {
                WebTokenRequest webTokenRequest = new WebTokenRequest(provider, "", AdalClientId);

                // webTokenRequest.Properties.Add("resource", "https://graph.windows.net");
                webTokenRequest.Properties.Add("resource", App.ServiceResourceUrl);

                // If the user selected a specific account, RequestTokenAsync will return a token for that account.
                // The user may be prompted for credentials or to authorize using that account with your app
                // If the user selected a provider, the user will be prompted for credentials to login to a new account
                WebTokenRequestResult webTokenRequestResult;
                if (prompt)
                {
                    webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);


                    ////result = await context.AcquireTokenAsync(AdalResourceId, AdalClientId, _returnUri, PromptBehavior.Auto, objUserIdtfr, "domain_hint=microsoft.com");
                }
                else
                {
                    webTokenRequestResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest);
                }
                // If a token was successfully returned, then store the WebAccount Id into local app data
                // This Id can be used to retrieve the account whenever needed. To later get a token with that account
                // First retrieve the account with FindAccountAsync, and include that webaccount 
                // as a parameter to RequestTokenAsync or RequestTokenSilentlyAsync
                if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
                {
                  
                    App.AccessToken = webTokenRequestResult.ResponseData[0].Token;

                    string szUserinfo = webTokenRequestResult.ResponseData[0].WebAccount.UserName;
                    if (!szUserinfo.ToLower().Contains("microsoft.com"))
                    {
                        await Utils.ShowPopUp("Not a valid user. App now exits");
                        Windows.UI.Xaml.Application.Current.Exit();
                    }
                    if (!string.IsNullOrEmpty(szUserinfo) && szUserinfo.Contains("@"))  //TODO: This is not always alias, for some users emailid and alias is differnt
                        App.szUserAlias = szUserinfo.Split('@').First();

                    App.szUserName = App.szUserAlias;
                    
                }