Ejemplo n.º 1
0
        private static AuthenticationContext GetAuthenticationContext(string userId, Permissions permissions)
        {
            var signedInUserID = permissions == Permissions.Delegated ? userId : Constants.AADTenantId;
            var tokenCache     = ADALTokenCache.Create(signedInUserID);

            return(new AuthenticationContext(Constants.Authority, tokenCache));
        }
Ejemplo n.º 2
0
        public static string GetAccessToken(string resource)
        {
            // get ClaimsPrincipal for current user
            ClaimsPrincipal currentUserClaims = ClaimsPrincipal.Current;
            string          signedInUserID    = currentUserClaims.FindFirst(ClaimTypes.NameIdentifier).Value;
            string          tenantID          = currentUserClaims.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string          userObjectID      = currentUserClaims.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            ApplicationDbContext db             = new ApplicationDbContext();
            ADALTokenCache       userTokenCache = new ADALTokenCache(signedInUserID);

            string urlAuthorityRoot   = ConfigurationManager.AppSettings["ida:AADInstance"];
            string urlAuthorityTenant = urlAuthorityRoot + tenantID;

            AuthenticationContext authenticationContext =
                new AuthenticationContext(urlAuthorityTenant, userTokenCache);

            Uri uriReplyUrl = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

            string           clientId         = ConfigurationManager.AppSettings["ida:ClientId"];
            string           clientSecret     = ConfigurationManager.AppSettings["ida:ClientSecret"];
            ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);

            UserIdentifier userIdentifier = new UserIdentifier(userObjectID, UserIdentifierType.UniqueId);

            AuthenticationResult authenticationResult =
                authenticationContext.AcquireTokenSilentAsync(resource, clientCredential, userIdentifier).Result;

            return(authenticationResult.AccessToken);
        }
Ejemplo n.º 3
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 = ADALTokenCache.Create(signedInUserID);

            return(new AuthenticationContext(authority, tokenCache));
        }
        public async Task <ActionResult> Purge()
        {
            try
            {
                await ADALTokenCache.PurgeAsync();

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View("Error"));
            }
        }
Ejemplo n.º 5
0
        public static ADALTokenCache GetTokenCache()
        {
            // get ClaimsPrincipal for current user
            ClaimsPrincipal currentUserClaims = ClaimsPrincipal.Current;
            string          signedInUserID    = currentUserClaims.FindFirst(ClaimTypes.NameIdentifier).Value;


            string userObjectID = currentUserClaims.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            ApplicationDbContext db             = new ApplicationDbContext();
            ADALTokenCache       userTokenCache = new ADALTokenCache(signedInUserID);

            return(userTokenCache);
        }
Ejemplo n.º 6
0
        public async Task ClearDataAsync(IDialogContext context, LuisResult result)
        {
            context.UserData.Clear();
            context.ConversationData.Clear();

            var user = await context.GetTeamsAccountAsync();

            var tokenCache = ADALTokenCache.Create(user.ObjectId);

            tokenCache.Clear();

            await context.SayAsync("User & Conversation data were cleared. Token cache was cleared");

            context.Wait(MessageReceived);
        }
Ejemplo n.º 7
0
        public async Task <string> GetTokenForApplication()
        {
            string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            string tenantID       = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            string userObjectID   = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
            ClientCredential clientcred = new ClientCredential(clientId, appKey);
            // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
            AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, ADALTokenCache.Create(signedInUserID));
            AuthenticationResult  authenticationResult  = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

            return(authenticationResult.AccessToken);
        }
Ejemplo n.º 8
0
        public void ConfigureAuth(IAppBuilder app)
        {
            string ClientId           = ConfigurationManager.AppSettings["ida:ClientID"];
            string Password           = ConfigurationManager.AppSettings["ida:Password"];
            string Authority          = string.Format(ConfigurationManager.AppSettings["ida:Authority"], "common");
            string GraphAPIIdentifier = ConfigurationManager.AppSettings["ida:GraphAPIIdentifier"];

            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.AcquireTokenByAuthorizationCode(
                            context.Code,
                            new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                            credential);

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

                        AuthenticationResult result2 = authContext.AcquireTokenSilent(
                            ConfigurationManager.AppSettings["ida:AzureResourceManagerIdentifier"],
                            credential,
                            new UserIdentifier(signedInUserUniqueName, UserIdentifierType.RequiredDisplayableId));

                        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));
                    }
                }
            });
        }