Esempio n. 1
0
        public static async Task <AuthenticationResult> AcquireTokenWithClientCredentialAsync()
        {
            AuthenticationResult result = null;
            ClientCredential     cred   = null;
            string ClientId             = null;
            string ClientSecret         = null;

            if (ctx.TokenCache.Count > 0)
            {
                ClientId     = CustomTokenCache.ReadData("Clientid.dat");
                ClientSecret = CustomTokenCache.ReadData("Sec.dat");
            }
            else
            {
                string keyvaultUri = ConfigurationManager.AppSettings["ServicePrincipalContextUri"];

                KeyVaultSecret spContext = await KeyVaultHelper.KeyVaultHelper.GetSecretFromMsiAsync(keyvaultUri);

                CustomTokenCache.WriteData("clientid.dat", spContext.ServicePrincipal.ClientId);
                CustomTokenCache.WriteData("Sec.dat", spContext.ServicePrincipal.ClientSecret);
                ClientId     = spContext.ServicePrincipal.ClientId;
                ClientSecret = spContext.ServicePrincipal.ClientSecret;
            }
            cred   = new ClientCredential(ClientId, ClientSecret);
            result = await ctx.AcquireTokenAsync(Resource, cred);



            return(result);
        }
Esempio n. 2
0
        public static async Task <AuthenticationResult> AcquireTokenWithSSOAsync(string clientId = null, string resourceId = null)
        {
            AuthenticationResult result = null;

            //Get the local upn from connected user
            //cache upn

            string upn = CustomTokenCache.ReadData("upn.dat");

            if (string.IsNullOrEmpty(upn))
            {
                upn = UserPrincipal.Current.UserPrincipalName;
                CustomTokenCache.WriteData("upn.dat", upn);
            }
            if (string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(resourceId))
            {
                try
                {
                    result = await ctx.AcquireTokenSilentAsync(Resource, ClientId).ConfigureAwait(false);
                }
                catch (AdalException)
                {
                    result = await ctx.AcquireTokenAsync(Resource, ClientId, new UserCredential(upn)).ConfigureAwait(false);
                }
            }
            else
            {
                try
                {
                    result = await ctx.AcquireTokenSilentAsync(resourceId, clientId).ConfigureAwait(false);
                }
                catch (AdalException)
                {
                    result = await ctx.AcquireTokenAsync(resourceId, clientId, new UserCredential(upn)).ConfigureAwait(false);
                }
            }

            return(result);
        }