Ejemplo n.º 1
0
        public async Task <ActionResult> ClearAdalCache()
        {
            await AdalTokenCache.ClearUserTokenCacheAsync();

            TempData["Message"] = "Login cache cleared successfully!";
            return(RedirectToAction("Index"));
        }
        public EnvironmentSetupHelper()
        {
            var datastore = new MemoryDataStore();

            AzureSession.DataStore = datastore;
            var profile   = new AzureSMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));
            var rmprofile = new AzureRMProfile(Path.Combine(AzureSession.ProfileDirectory, AzureSession.ProfileFile));

            rmprofile.Environments.Add("foo", AzureEnvironment.PublicEnvironments.Values.FirstOrDefault());
            rmprofile.Context = new AzureContext(new AzureSubscription(), new AzureAccount(), rmprofile.Environments["foo"], new AzureTenant());
            rmprofile.Context.Subscription.Environment = "foo";
            if (AzureRmProfileProvider.Instance.Profile == null)
            {
                AzureRmProfileProvider.Instance.Profile = rmprofile;
            }

            AzureSession.DataStore = datastore;
            ProfileClient          = new ProfileClient(profile);

            // Ignore SSL errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;

            AdalTokenCache.ClearCookies();

            // Set RunningMocked
            TestMockSupport.RunningMocked = HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback;
        }
Ejemplo n.º 3
0
        public EnvironmentSetupHelper()
        {
            TestExecutionHelpers.SetUpSessionAndProfile();
            var datastore = new MemoryDataStore();

            AzureSession.Instance.DataStore = datastore;
            var rmprofile = new AzureRmProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));

            rmprofile.EnvironmentTable.Add("foo", new AzureEnvironment(AzureEnvironment.PublicEnvironments.Values.FirstOrDefault()));
            rmprofile.DefaultContext = new AzureContext(new AzureSubscription(), new AzureAccount(), rmprofile.EnvironmentTable["foo"], new AzureTenant());
            rmprofile.DefaultContext.Subscription.SetEnvironment("foo");
            if (AzureRmProfileProvider.Instance.Profile == null)
            {
                AzureRmProfileProvider.Instance.Profile = rmprofile;
            }

            AzureSession.Instance.DataStore = datastore;

            // Ignore SSL errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;

#if !NETSTANDARD
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            var profile = new AzureSMProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));
            ProfileClient = new ProfileClient(profile);
            AdalTokenCache.ClearCookies();
#endif
            // Set RunningMocked
            TestMockSupport.RunningMocked = HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback;

            if (File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".azure", "testcredentials.json")))
            {
                SetEnvironmentVariableFromCredentialFile();
            }
        }
Ejemplo n.º 4
0
        private AuthenticationResult DoAcquireToken(
            AdalConfiguration config,
            PromptBehavior promptBehavior,
            Action <string> promptAction,
            string userId,
            SecureString password)
        {
            AuthenticationResult result;
            var context = CreateContext(config);

            TracingAdapter.Information(
                Resources.UPNAcquireTokenContextTrace,
                context.Authority,
                context.CorrelationId,
                context.ValidateAuthority);
            TracingAdapter.Information(
                Resources.UPNAcquireTokenConfigTrace,
                config.AdDomain,
                config.AdEndpoint,
                config.ClientId,
                config.ClientRedirectUri);
            if (string.IsNullOrEmpty(userId))
            {
                if (promptBehavior != PromptBehavior.Never)
                {
                    AdalTokenCache.ClearCookies();
                }

                result = context.AcquireToken(
                    config.ResourceClientUri,
                    config.ClientId,
                    config.ClientRedirectUri,
                    promptBehavior,
                    UserIdentifier.AnyUser,
                    AdalConfiguration.EnableEbdMagicCookie);
            }
            else
            {
                if (password == null)
                {
                    result = context.AcquireToken(
                        config.ResourceClientUri,
                        config.ClientId,
                        config.ClientRedirectUri,
                        promptBehavior,
                        new UserIdentifier(userId, UserIdentifierType.RequiredDisplayableId),
                        AdalConfiguration.EnableEbdMagicCookie);
                }
                else
                {
                    UserCredential credential = new UserCredential(userId, password);
                    result = context.AcquireToken(config.ResourceClientUri, config.ClientId, credential);
                }
            }
            return(result);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Get an instance of AuthenticationContext
        /// </summary>
        public static AuthenticationContext GetAuthenticationContext(ClaimsIdentity claimsIdentity, Permissions permissions)
        {
            var tenantID       = claimsIdentity.GetTenantId();
            var userId         = claimsIdentity.GetObjectIdentifier();
            var signedInUserID = permissions == Permissions.Delegated ? userId : tenantID;

            var authority  = string.Format("{0}{1}", Constants.AADInstance, tenantID);
            var tokenCache = new AdalTokenCache(signedInUserID);

            return(new AuthenticationContext(authority, tokenCache));
        }
Ejemplo n.º 6
0
        public static void ConfigureAuth(IAppBuilder app)
        {
            string commonAuthority = string.Format(Config.Authority, "common");

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                ExpireTimeSpan    = new TimeSpan(3, 0, 0),
                SlidingExpiration = true
            });

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                //ProtocolValidator = new Microsoft.IdentityModel.Protocols.OpenIdConnectProtocolValidator() { RequireNonce = false },
                ClientId                  = Config.ClientId,
                Authority                 = commonAuthority,
                UseTokenLifetime          = false,
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    // we inject our own multitenant validation logic
                    ValidateIssuer = false,
                },
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = (context) =>
                    {
                        if (IsApiRequest(context.Request))
                        {
                            context.HandleResponse();
                            context.OwinContext.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
                        }
                        else
                        {
                            // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                            // this allows you to deploy your app (to Azure Web Sites, for example) without having to change settings
                            // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                            string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;

                            object obj = null;
                            if (context.OwinContext.Environment.TryGetValue("Authority", out obj))
                            {
                                string authority = obj as string;
                                if (authority != null)
                                {
                                    context.ProtocolMessage.IssuerAddress = authority;
                                }
                            }
                            if (context.OwinContext.Environment.TryGetValue("DomainHint", out obj))
                            {
                                string domainHint = obj as string;
                                if (domainHint != null)
                                {
                                    context.ProtocolMessage.SetParameter("domain_hint", domainHint);
                                }
                            }
                            if (context.OwinContext.Environment.TryGetValue("owin.RequestQueryString", out obj))
                            {
                                var queryString = obj as string;
                                if (queryString.StartsWith("domain="))
                                {
                                    var domain = queryString.Substring(7).Replace(".onmicrosoft.com", null);
                                    context.ProtocolMessage.PostLogoutRedirectUri = $"{appBaseUrl}/{domain}";
                                }
                                else
                                {
                                    context.ProtocolMessage.PostLogoutRedirectUri = new UrlHelper(HttpContext.Current.Request.RequestContext).Action(
                                        "Index", "Home", null, HttpContext.Current.Request.Url.Scheme
                                        );
                                }
                            }
                            else
                            {
                                context.ProtocolMessage.PostLogoutRedirectUri = new UrlHelper(HttpContext.Current.Request.RequestContext).Action(
                                    "Index", "Home", null, HttpContext.Current.Request.Url.Scheme
                                    );
                            }
                            context.ProtocolMessage.RedirectUri = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path);
                            context.ProtocolMessage.Resource    = Config.AzureResourceManagerIdentifier;
                        }
                        return(Task.FromResult(0));
                    },
                    AuthorizationCodeReceived = (context) =>
                    {
                        ClientCredential credential   = new ClientCredential(Config.ClientId, Config.Password);
                        string tenantID               = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        string signedInUserUniqueName = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value.Split('#')[context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

                        var tokenCache = new AdalTokenCache(signedInUserUniqueName);
                        tokenCache.Clear();

                        AuthenticationContext authContext = new AuthenticationContext(string.Format(Config.Authority, tenantID), tokenCache);

                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                            context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, Config.GraphAPIIdentifier);

                        return(Task.FromResult(0));
                    },
                    SecurityTokenValidated = (context) =>
                    {
                        // we use this notification for injecting our custom logic
                        // retriever caller data from the incoming principal
                        string issuer = context.AuthenticationTicket.Identity.FindFirst("iss").Value;
                        if (!issuer.StartsWith("https://sts.windows.net/"))
                        {
                            // the caller is not from a trusted issuer - throw to block the authentication flow
                            throw new System.IdentityModel.Tokens.SecurityTokenValidationException();
                        }
                        return(Task.FromResult(0));
                    }
                    //AuthenticationFailed = (context) =>
                    //{
                    //    context.OwinContext.Response.Redirect(new UrlHelper(HttpContext.Current.Request.RequestContext).
                    //        Action("Index", "Home", null, HttpContext.Current.Request.Url.Scheme));
                    //    context.HandleResponse(); // Suppress the exception
                    //        return Task.FromResult(0);
                    //}
                }
            });
        }
Ejemplo n.º 7
0
        public void ConfigureAuth(IAppBuilder app)
        {
            var clientId  = Settings.ProvisionerClient;
            var password  = Settings.ProvisionerPassword;
            var authority = string.Format(Settings.LoginUri, "common");
            var azureResourceManagerIdentifier = Settings.ApiEndpointUri;

            // Set authentication types
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = clientId,
                Authority = authority,

                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = false,
                },

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = (context) =>
                    {
                        if (!context.Request.Path.ToString().Contains("Account"))
                        {
                            var redirectToSignUp = context.Request.Path.ToString().Contains("SignUp");

                            context.HandleResponse();
                            context.Response.Redirect(string.Format("Login?redirectToSignUp={0}", redirectToSignUp));
                        }
                        else
                        {
                            object obj;

                            if (context.OwinContext.Environment.TryGetValue("Authority", out obj))
                            {
                                var auth = obj as string;

                                if (auth != null)
                                {
                                    context.ProtocolMessage.IssuerAddress = auth;
                                }
                            }

                            if (context.OwinContext.Environment.TryGetValue("DomainHint", out obj))
                            {
                                var domainHint = obj as string;

                                if (domainHint != null)
                                {
                                    context.ProtocolMessage.SetParameter("domain_hint", domainHint);
                                }
                            }

                            context.ProtocolMessage.RedirectUri           = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path);
                            context.ProtocolMessage.PostLogoutRedirectUri = new UrlHelper(HttpContext.Current.Request.RequestContext).Action("Index", "Home", null, HttpContext.Current.Request.Url.Scheme);
                            context.ProtocolMessage.Resource = azureResourceManagerIdentifier;
                        }

                        return(Task.FromResult(0));
                    },

                    AuthorizationCodeReceived = (context) =>
                    {
                        var credential             = new ClientCredential(clientId, password);
                        var tenantId               = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        var signedInUserUniqueName = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value.Split('#').Last();

                        var tokenCache = new AdalTokenCache(signedInUserUniqueName);
                        tokenCache.Clear();

                        var authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId), tokenCache);
                        var result      = authContext.AcquireTokenByAuthorizationCode(context.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential);

                        return(Task.FromResult(0));
                    },

                    SecurityTokenValidated = (context) =>
                    {
                        var issuer = context.AuthenticationTicket.Identity.FindFirst("iss").Value;

                        if (!issuer.StartsWith("https://sts.windows.net/"))
                        {
                            throw new System.IdentityModel.Tokens.SecurityTokenValidationException();
                        }

                        return(Task.FromResult(0));
                    }
                }
            });
        }
        public EnvironmentSetupHelper()
        {
            var module = GetModuleManifest(RmDirectory, "AzureRM.Accounts");

            if (string.IsNullOrWhiteSpace(module))
            {
                throw new InvalidOperationException("Could not find Accounts module");
            }

            LogIfNotNull($"Accounts Module path: {module}");
            RMProfileModule = module;
            module          = GetModuleManifest(RmDirectory, "AzureRM.Resources");
            LogIfNotNull($"Resources Module path: {module}");
            RMResourceModule = module;
            module           = GetModuleManifest(RmDirectory, "AzureRM.Insights");
            LogIfNotNull($"Insights Module path: {module}");
            RMInsightsModule = module;
            module           = GetModuleManifest(RmDirectory, "AzureRM.Storage");
            LogIfNotNull($"Storage Management Module path: {module}");
            RMStorageModule = module;
            module          = GetModuleManifest(StorageDirectory, "Azure.Storage");
            LogIfNotNull($"Storage Data Plane Module path: {module}");
            RMStorageDataPlaneModule = module;
            module = GetModuleManifest(RmDirectory, "AzureRM.OperationalInsights");
            LogIfNotNull($"Storage Data Plane Module path: {module}");
            RMOperationalInsightsModule = module;
            module = GetModuleManifest(RmDirectory, "AzureRM.Network");
            LogIfNotNull($"Network Module path: {module}");
            RMNetworkModule = module;

            module = GetModuleManifest(StackRmDirectory, "AzureRM.Accounts");
            LogIfNotNull($"Stack Accounts Module path: {module}");
            StackRMProfileModule = module;
            module = GetModuleManifest(StackRmDirectory, "AzureRM.Resources");
            LogIfNotNull($"Stack Resources Module path: {module}");
            StackRMResourceModule = module;
            module = GetModuleManifest(StackRmDirectory, "AzureRM.Storage");
            LogIfNotNull($"Stack Storage Management Plane Module path: {module}");
            StackRMStorageModule = module;
            module = GetModuleManifest(StackStorageDirectory, "Azure.Storage");
            LogIfNotNull($"Stack Storage Data Plane Module path: {module}");
            StackRMStorageDataPlaneModule = module;

            TestExecutionHelpers.SetUpSessionAndProfile();
            IDataStore datastore = new MemoryDataStore();

            if (AzureSession.Instance.DataStore != null && (AzureSession.Instance.DataStore is MemoryDataStore))
            {
                datastore = AzureSession.Instance.DataStore;
            }

            AzureSession.Instance.DataStore = datastore;
            var rmprofile = new AzureRmProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));

            rmprofile.EnvironmentTable.Add("foo", new AzureEnvironment(AzureEnvironment.PublicEnvironments.Values.FirstOrDefault()));
            rmprofile.DefaultContext = new AzureContext(new AzureSubscription(), new AzureAccount(), rmprofile.EnvironmentTable["foo"], new AzureTenant());
            rmprofile.DefaultContext.Subscription.SetEnvironment("foo");
            if (AzureRmProfileProvider.Instance.Profile == null)
            {
                AzureRmProfileProvider.Instance.Profile = rmprofile;
            }

            AzureSession.Instance.DataStore = datastore;

            // Ignore SSL errors
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => true;

#if !NETSTANDARD
            ServiceManagementProfileProvider.InitializeServiceManagementProfile();
            var profile = new AzureSMProfile(Path.Combine(AzureSession.Instance.ProfileDirectory, AzureSession.Instance.ProfileFile));
            ProfileClient = new ProfileClient(profile);
            AdalTokenCache.ClearCookies();
#endif
            // Set RunningMocked
            TestMockSupport.RunningMocked = HttpMockServer.GetCurrentMode() == HttpRecorderMode.Playback;

            if (File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".azure", "testcredentials.json")))
            {
                SetEnvironmentVariableFromCredentialFile();
            }
        }
Ejemplo n.º 9
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions {
            });
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                ClientId  = ClientId,
                Authority = Authority,
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    // we inject our own multitenant validation logic
                    ValidateIssuer = false,
                },
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = (context) =>
                    {
                        // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                        // this allows you to deploy your app (to Azure Web Sites, for example) without having to change settings
                        // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                        //string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;

                        object obj = null;
                        if (context.OwinContext.Environment.TryGetValue("Authority", out obj))
                        {
                            string authority = obj as string;
                            if (authority != null)
                            {
                                context.ProtocolMessage.IssuerAddress = authority;
                            }
                        }
                        if (context.OwinContext.Environment.TryGetValue("DomainHint", out obj))
                        {
                            string domainHint = obj as string;
                            if (domainHint != null)
                            {
                                context.ProtocolMessage.SetParameter("domain_hint", domainHint);
                            }
                        }
                        context.ProtocolMessage.RedirectUri           = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path);
                        context.ProtocolMessage.PostLogoutRedirectUri = new UrlHelper(HttpContext.Current.Request.RequestContext).Action("Index", "Home", null, HttpContext.Current.Request.Url.Scheme);
                        context.ProtocolMessage.Resource = GraphApiIdentifier;
                        return(Task.FromResult(0));
                    },
                    AuthorizationCodeReceived = (context) =>
                    {
                        ClientCredential credential   = new ClientCredential(ClientId, Password);
                        string tenantID               = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        string signedInUserUniqueName = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value.Split('#')[context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value.Split('#').Length - 1];

                        AdalTokenCache cache = new AdalTokenCache(signedInUserUniqueName);

                        cache.Clear();

                        AuthenticationContext authContext = new AuthenticationContext(
                            String.Format("https://login.microsoftonline.com/{0}", tenantID),
                            new AdalTokenCache(signedInUserUniqueName));

                        var items = authContext.TokenCache.ReadItems().ToList();

                        AuthenticationResult result1 = authContext.AcquireTokenByAuthorizationCodeAsync(
                            context.Code,
                            new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                            credential).GetAwaiter().GetResult();

                        items = authContext.TokenCache.ReadItems().ToList();

                        AuthenticationResult result2 = authContext.AcquireTokenSilentAsync(
                            AzureResourceManagerIdentifier,
                            credential,
                            new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId)).GetAwaiter().GetResult();

                        items = authContext.TokenCache.ReadItems().ToList();

                        return(Task.FromResult(0));
                    },
                    // we use this notification for injecting our custom logic
                    SecurityTokenValidated = (context) =>
                    {
                        // retriever caller data from the incoming principal
                        string issuer = context.AuthenticationTicket.Identity.FindFirst("iss").Value;
                        if (!issuer.StartsWith("https://sts.windows.net/"))
                        {
                            // the caller is not from a trusted issuer - throw to block the authentication flow
                            throw new System.IdentityModel.Tokens.SecurityTokenValidationException();
                        }

                        return(Task.FromResult(0));
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.OwinContext.Response.Redirect(new UrlHelper(HttpContext.Current.Request.RequestContext).
                                                              Action("Error", "Home", new { ExceptionDetails = context.Exception.Message }, HttpContext.Current.Request.Url.Scheme));
                        context.HandleResponse();                                 // Suppress the exception
                        return(Task.FromResult(0));
                    }
                }
            });
        }