예제 #1
0
        protected Task <TokenCacheInfo> GetAuthorizationResult(CustomTokenCache tokenCache, string tenantId, string user = null, string resource = null)
        {
            var tcs = new TaskCompletionSource <TokenCacheInfo>();

            resource = resource ?? Constants.CSMResources[(int)AzureEnvironments];

            TokenCacheInfo found;

            if (tokenCache.TryGetValue(tenantId, resource, out found))
            {
                tcs.SetResult(found);
                return(tcs.Task);
            }

            var thread = new Thread(() =>
            {
                try
                {
                    var azureEnvironment = this.AzureEnvironments;
                    var authority        = String.Format("{0}/{1}", Constants.AADLoginUrls[(int)azureEnvironment], tenantId);
                    var context          = new AuthenticationContext(
                        authority: authority,
                        validateAuthority: true,
                        tokenCache: tokenCache);

                    AuthenticationResult result = null;
                    if (!string.IsNullOrEmpty(user))
                    {
                        result = context.AcquireToken(
                            resource: resource,
                            clientId: Constants.AADClientId,
                            redirectUri: new Uri(Constants.AADRedirectUri),
                            promptBehavior: PromptBehavior.Never,
                            userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId));
                    }
                    else
                    {
                        result = context.AcquireToken(
                            resource: resource,
                            clientId: Constants.AADClientId,
                            redirectUri: new Uri(Constants.AADRedirectUri),
                            promptBehavior: PromptBehavior.Always);
                    }

                    var cacheInfo = new TokenCacheInfo(resource, result);
                    tokenCache.Add(cacheInfo);
                    tcs.TrySetResult(cacheInfo);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Name = "AcquireTokenThread";
            thread.Start();

            return(tcs.Task);
        }
예제 #2
0
        protected async Task <TokenCacheInfo> GetAuthorizationResultBySpn(CustomTokenCache tokenCache, string tenantId, string appId, X509Certificate2 certificate, string resource)
        {
            TokenCacheInfo found;

            if (tokenCache.TryGetValue(tenantId, resource, out found))
            {
                return(found);
            }

            var helper        = new JwtHelper();
            var tokenEndpoint = string.Format("{0}/{1}/oauth2/token", Constants.AADLoginUrls[(int)this.AzureEnvironments], tenantId);
            var token         = await helper.AcquireTokenByX509(tenantId, appId, certificate, resource, tokenEndpoint);

            var cacheInfo = new TokenCacheInfo(tenantId, appId, "_certificate_", resource, token);

            tokenCache.Add(cacheInfo);
            return(cacheInfo);
        }
예제 #3
0
        protected async Task <TokenCacheInfo> GetAuthorizationResultByRefreshToken(CustomTokenCache tokenCache, TokenCacheInfo cacheInfo)
        {
            var azureEnvironment = this.AzureEnvironments;
            var authority        = String.Format("{0}/{1}", Constants.AADLoginUrls[(int)azureEnvironment], cacheInfo.TenantId);
            var context          = new AuthenticationContext(
                authority: authority,
                validateAuthority: true,
                tokenCache: tokenCache);

            AuthenticationResult result = await context.AcquireTokenByRefreshTokenAsync(
                refreshToken : cacheInfo.RefreshToken,
                clientId : Constants.AADClientId,
                resource : cacheInfo.Resource);

            var ret = new TokenCacheInfo(cacheInfo.Resource, result);

            ret.TenantId      = cacheInfo.TenantId;
            ret.DisplayableId = cacheInfo.DisplayableId;
            tokenCache.Add(ret);
            return(ret);
        }
예제 #4
0
        protected async Task <TokenCacheInfo> GetAuthorizationResultByRefreshToken(CustomTokenCache tokenCache, TokenCacheInfo cacheInfo)
        {
            var authority = String.Format("{0}/{1}", ARMConfiguration.AADLoginUrl, cacheInfo.TenantId);
            var context   = new AuthenticationContext(
                authority: authority,
                validateAuthority: true,
                tokenCache: tokenCache);

            AuthenticationResult result = await context.AcquireTokenByRefreshTokenAsync(
                refreshToken : cacheInfo.RefreshToken,
                clientId : !string.IsNullOrEmpty(cacheInfo.ClientId)?cacheInfo.ClientId : Constants.AADClientId,
                resource : cacheInfo.Resource);

            var ret = new TokenCacheInfo(cacheInfo.Resource, result);

            ret.TenantId      = cacheInfo.TenantId;
            ret.DisplayableId = cacheInfo.DisplayableId;
            ret.ClientId      = cacheInfo.ClientId;
            tokenCache.Add(ret);
            return(ret);
        }
예제 #5
0
        protected TokenCacheInfo GetAuthorizationResultByUpn(CustomTokenCache tokenCache, string tenantId, string username, string password, string resource)
        {
            TokenCacheInfo found;

            if (tokenCache.TryGetValue(tenantId, resource, out found))
            {
                return(found);
            }

            var authority = String.Format("{0}/{1}", ARMConfiguration.AADLoginUrl, tenantId);
            var context   = new AuthenticationContext(
                authority: authority,
                validateAuthority: true,
                tokenCache: tokenCache);
            var credential = new UserCredential(username, password);
            var result     = context.AcquireToken(resource, Constants.AADClientId, credential);

            var cacheInfo = new TokenCacheInfo(resource, result);

            tokenCache.Add(cacheInfo);
            return(cacheInfo);
        }
예제 #6
0
        protected TokenCacheInfo GetAuthorizationResultBySpn(CustomTokenCache tokenCache, string tenantId, string appId, string appKey, string resource)
        {
            TokenCacheInfo found;

            if (tokenCache.TryGetValue(tenantId, resource, out found))
            {
                return(found);
            }

            var azureEnvironment = this.AzureEnvironments;
            var authority        = String.Format("{0}/{1}", Constants.AADLoginUrls[(int)azureEnvironment], tenantId);
            var context          = new AuthenticationContext(
                authority: authority,
                validateAuthority: true,
                tokenCache: tokenCache);
            var credential = new ClientCredential(appId, appKey);
            var result     = context.AcquireToken(resource, credential);

            var cacheInfo = new TokenCacheInfo(tenantId, appId, appKey, resource, result);

            tokenCache.Add(cacheInfo);
            return(cacheInfo);
        }
예제 #7
0
        public async Task AzLogin()
        {
            this.TokenStorage.ClearCache();
            this.TenantStorage.ClearCache();

            var tokens = GetAzLoginTokens();

            var            tokenCache  = new CustomTokenCache();
            var            tenantCache = this.TenantStorage.GetCache();
            TokenCacheInfo recentInfo  = null;

            foreach (var token in tokens)
            {
                var  result = token.ToTokenCacheInfo();
                Guid unused;
                if (!Guid.TryParse(result.TenantId, out unused))
                {
                    continue;
                }

                tokenCache.Add(result);

                var tenantId = result.TenantId;
                var info     = new TenantCacheInfo
                {
                    tenantId    = tenantId,
                    displayName = "unknown",
                    domain      = tenantId
                };

                Utils.Trace.WriteLine(string.Format("User: {0}, Tenant: {1}", result.DisplayableId, tenantId));
                try
                {
                    var subscriptions = await GetSubscriptions(result);

                    Utils.Trace.WriteLine(string.Format("\tThere are {0} subscriptions", subscriptions.Length));

                    info.subscriptions = subscriptions.Select(subscription => new SubscriptionCacheInfo
                    {
                        subscriptionId = subscription.subscriptionId,
                        displayName    = subscription.displayName
                    }).ToArray();

                    if (recentInfo == null || info.subscriptions.Length > 0)
                    {
                        recentInfo = result;
                    }

                    foreach (var subscription in subscriptions)
                    {
                        Utils.Trace.WriteLine(string.Format("\tSubscription {0} ({1})", subscription.subscriptionId, subscription.displayName));
                    }
                }
                catch (Exception ex)
                {
                    Utils.Trace.WriteLine(string.Format("\t{0}!", ex.Message));
                }

                tenantCache[tenantId] = info;
                if (!String.IsNullOrEmpty(info.domain) && info.domain != "unknown")
                {
                    tenantCache[info.domain] = info;
                }

                Utils.Trace.WriteLine(string.Empty);
            }

            if (recentInfo != null)
            {
                this.TokenStorage.SaveRecentToken(recentInfo, Constants.CSMResources[(int)AzureEnvironments]);
            }

            this.TokenStorage.SaveCache(tokenCache);
            this.TenantStorage.SaveCache(tenantCache);
        }
예제 #8
0
        protected Task <TokenCacheInfo> GetAuthorizationResult(CustomTokenCache tokenCache, string tenantId, string user = null, string resource = null)
        {
            var tcs = new TaskCompletionSource <TokenCacheInfo>();

            resource = resource ?? ARMConfiguration.ARMResource;

            TokenCacheInfo found;

            if (tokenCache.TryGetValue(tenantId, resource, out found))
            {
                tcs.SetResult(found);
                return(tcs.Task);
            }

            var thread = new Thread(() =>
            {
                try
                {
                    var authority = String.Format("{0}/{1}", ARMConfiguration.AADLoginUrl, tenantId);
                    var context   = new AuthenticationContext(
                        authority: authority,
                        validateAuthority: true,
                        tokenCache: tokenCache);

                    AuthenticationResult result = null;
                    if (!string.IsNullOrEmpty(user))
                    {
                        try
                        {
                            result = context.AcquireToken(
                                resource: resource,
                                clientId: Constants.AADClientId,
                                redirectUri: new Uri(Constants.AADRedirectUri),
                                promptBehavior: PromptBehavior.Never,
                                userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId));
                        }
                        catch (AdalException adalEx)
                        {
                            if (!string.Equals(adalEx.ErrorCode, "interaction_required", StringComparison.OrdinalIgnoreCase) &&
                                adalEx.Message.IndexOf("user_interaction_required") < 0)
                            {
                                throw;
                            }

                            result = context.AcquireToken(
                                resource: resource,
                                clientId: Constants.AADClientId,
                                redirectUri: new Uri(Constants.AADRedirectUri),
                                promptBehavior: PromptBehavior.Auto,
                                userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId));
                        }
                    }
                    else
                    {
                        result = context.AcquireToken(
                            resource: resource,
                            clientId: Constants.AADClientId,
                            redirectUri: new Uri(Constants.AADRedirectUri),
                            promptBehavior: PromptBehavior.Always);
                    }

                    var cacheInfo = new TokenCacheInfo(resource, result);
                    tokenCache.Add(cacheInfo);
                    tcs.TrySetResult(cacheInfo);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Name = "AcquireTokenThread";
            thread.Start();

            return(tcs.Task);
        }
예제 #9
0
        protected Task <TokenCacheInfo> GetAuthorizationResult(CustomTokenCache tokenCache, string tenantId, string user = null, string resource = null)
        {
            var tcs = new TaskCompletionSource <TokenCacheInfo>();

            resource = resource ?? Constants.CSMResources[(int)AzureEnvironments];

            TokenCacheInfo found;

            if (tokenCache.TryGetValue(tenantId, resource, out found))
            {
                tcs.SetResult(found);
                return(tcs.Task);
            }

            var thread = new Thread(async() =>
            {
                try
                {
                    var azureEnvironment = this.AzureEnvironments;
                    var authority        = String.Format("{0}/{1}", Constants.AADLoginUrls[(int)azureEnvironment], tenantId);
                    var context          = new AuthenticationContext(
                        authority: authority,
                        validateAuthority: true,
                        tokenCache: tokenCache);

                    AuthenticationResult result = null;
                    if (!string.IsNullOrEmpty(user))
                    {
                        try
                        {
#if NET471
                            result = await context.AcquireTokenAsync(
                                resource: resource,
                                clientId: Constants.AADClientId,
                                redirectUri: new Uri(Constants.AADRedirectUri),
                                parameters: new PlatformParameters(PromptBehavior.Never),
                                userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId));
#endif
#if NETCOREAPP2_0
                            result = await context.AcquireTokenAsync(
                                resource: resource,
                                clientId: Constants.AADClientId,
                                redirectUri: new Uri(Constants.AADRedirectUri),
                                parameters: new PlatformParameters(),
                                userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId));
#endif
                        }
                        catch (AdalException adalEx)
                        {
                            if (adalEx.Message.IndexOf("user_interaction_required") < 0)
                            {
                                throw;
                            }
#if NET471
                            result = await context.AcquireTokenAsync(
                                resource: resource,
                                clientId: Constants.AADClientId,
                                redirectUri: new Uri(Constants.AADRedirectUri),
                                parameters: new PlatformParameters(PromptBehavior.Auto),
                                userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId));
#endif
#if NETCOREAPP2_0
                            result = await context.AcquireTokenAsync(
                                resource: resource,
                                clientId: Constants.AADClientId,
                                redirectUri: new Uri(Constants.AADRedirectUri),
                                parameters: new PlatformParameters(),
                                userId: new UserIdentifier(user, UserIdentifierType.OptionalDisplayableId));
#endif
                        }
                    }
                    else
                    {
#if NET471
                        result = await context.AcquireTokenAsync(
                            resource: resource,
                            clientId: Constants.AADClientId,
                            redirectUri: new Uri(Constants.AADRedirectUri),
                            parameters: new PlatformParameters(PromptBehavior.Always));
#endif
#if NETCOREAPP2_0
                        result = await context.AcquireTokenAsync(
                            resource: resource,
                            clientId: Constants.AADClientId,
                            redirectUri: new Uri(Constants.AADRedirectUri),
                            parameters: new PlatformParameters());
#endif
                    }

                    var cacheInfo = new TokenCacheInfo(resource, result);
                    tokenCache.Add(cacheInfo);
                    tcs.TrySetResult(cacheInfo);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Name = "AcquireTokenThread";
            thread.Start();

            return(tcs.Task);
        }