// If the javascript issues an OIDC authorize reuest, and it succeeds, the user is already logged
        // into AAD.  Since the AAD session cookie has changed, we need to check if the same use is still
        // logged in.
        public static Task AuthorizationCodeRecieved(AuthorizationCodeReceivedNotification notification)
        {
            // If the successful authorize request was issued by the SingleSignOut javascript
            if (notification.AuthenticationTicket.Properties.RedirectUri.Contains("SessionChanged"))
            {
                // Clear the SingleSignOutCookie
                notification.Response.Cookies.Append("SingleSignOut" + clientId, "");

                Claim existingUserObjectId = notification.OwinContext.Authentication.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");
                Claim incomingUserObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");

                if (existingUserObjectId.Value != null && incomingUserObjectId != null)
                {
                    // If a different user is logged into AAD
                    if (existingUserObjectId.Value != incomingUserObjectId.Value)
                    {
                        // No need to clear the session state here. It has already been
                        // updated with the new user's session state in SecurityTokenValidated.
                        notification.Response.Redirect("Account/SingleSignOut");
                        notification.HandleResponse();
                    }
                    // If the same user is logged into AAD
                    else if (existingUserObjectId.Value == incomingUserObjectId.Value)
                    {
                        // No need to clear the session state, SecurityTokenValidated will do so.
                        // Simply redirect the iframe to a page other than SingleSignOut to reset
                        // the timer in the javascript.
                        notification.Response.Redirect("/");
                        notification.HandleResponse();
                    }
                }
            }

            return(Task.FromResult <object>(null));
        }
コード例 #2
0
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            // If there is a code in the OpenID Connect response, redeem it for an access token and store it away.
            var    code         = context.Code;
            string userObjectId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            SampleTokenCache tokenCache = new SampleTokenCache(userObjectId);

            var credential = new ClientCredential(ClientSecret);

            var cca = new ConfidentialClientApplication(
                ClientId,
                context.Request.Uri.ToString(),
                credential,
                tokenCache.GetMsalCacheInstance(),
                null);


            try
            {
                var result = await cca.AcquireTokenByAuthorizationCodeAsync(code, Scopes);
            }
            catch (MsalException ex)
            {
                context.HandleResponse();
                context.Response.Redirect($"/error/index?message={ex.Message}");
            }
        }
コード例 #3
0
        public async Task HandleOpenIdAuthorizationCodeAsync(
            AuthorizationCodeReceivedNotification authorizationCodeReceived)
        {
            string tokenAsBase64 =
                JwtTokenHelper.CreateSecurityTokenDescriptor(authorizationCodeReceived.JwtSecurityToken.Claims,
                    _jwtOptions).CreateTokenAsBase64();

            authorizationCodeReceived.AuthenticationTicket.Properties.RedirectUri +=
                string.Format("&{0}={1}", _jwtOptions.JwtTokenParameterName, tokenAsBase64);

            if (_createConsentOptions.CreateConsentAsync != null)
            {
                await _createConsentOptions.CreateConsentAsync(authorizationCodeReceived.Response,
                    new Uri(authorizationCodeReceived.AuthenticationTicket.Properties.RedirectUri));

                authorizationCodeReceived.HandleResponse();
            }
            else
            {
                string implicitConsent = string.Format("&{0}={1}", _consentHandlerOptions.ConsentParameterName,
                    Uri.EscapeDataString("implicit"));
                authorizationCodeReceived.AuthenticationTicket.Properties.RedirectUri += implicitConsent;
            }

        }
コード例 #4
0
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            string            signedInUserId = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            SessionTokenCache tokenCache     = new SessionTokenCache(
                signedInUserId,
                notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase);
            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                appId,
                redirectUri,
                new ClientCredential(appPassword),
                tokenCache.GetMsalCacheInstance(),
                null);

            try
            {
                var result = await cca.AcquireTokenByAuthorizationCodeAsync(notification.Code, scopes);
            }
            catch (MsalException ex)
            {
                string message, debug;
                message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
                debug   = ex.Message;
                notification.HandleResponse();
                notification.Response.Redirect("/Home/Error?message=" + message + "&debug=" + debug);
            }
        }
コード例 #5
0
        private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            context.HandleResponse();
            var token = context.JwtSecurityToken.ToString();

            context.Response.Redirect(string.Format("/Main.aspx?Token={0}", token));
            return(Task.FromResult(0));
        }
コード例 #6
0
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification)
        {
            var idClient = ConfidentialClientApplicationBuilder.Create(appId)
                           .WithRedirectUri(redirectUri)
                           .WithClientSecret(appSecret)
                           .Build();

            var signedInUserId = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            var tokenStore     = new SessionTokenStore(signedInUserId, HttpContext.Current);

            tokenStore.Initialize(idClient.UserTokenCache);

            try
            {
                string[] scopes = graphScopes.Split(' ');

                var result = await idClient.AcquireTokenByAuthorizationCode(
                    scopes, notification.Code).ExecuteAsync();

                var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken);

                var cachedUser = new CachedUser()
                {
                    DisplayName = userDetails.DisplayName,
                    Email       = string.IsNullOrEmpty(userDetails.Mail) ?
                                  userDetails.UserPrincipalName : userDetails.Mail,
                    Avatar = string.Empty
                };

                tokenStore.SaveUserDetails(cachedUser);
            }
            catch (MsalException ex)
            {
                string message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
            catch (Microsoft.Graph.ServiceException ex)
            {
                string message = "GetUserDetailsAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
        }
コード例 #7
0
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification)
        {
            notification.HandleCodeRedemption();

            var idClient = ConfidentialClientApplicationBuilder.Create(appId)
                           .WithRedirectUri(redirectUri)
                           .WithClientSecret(appSecret)
                           .Build();

            var signedInUser = new ClaimsPrincipal(notification.AuthenticationTicket.Identity);
            var tokenStore   = new SessionTokenStore(idClient.UserTokenCache, HttpContext.Current, signedInUser);

            try
            {
                string[] scopes = graphScopes.Split(' ');

                var result = await idClient.AcquireTokenByAuthorizationCode(
                    scopes, notification.Code).ExecuteAsync();

                var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken);

                var handler   = new JwtSecurityTokenHandler();
                var jsonToken = handler.ReadToken(result.IdToken) as JwtSecurityToken;

                var sid = jsonToken.Claims.First(claim => claim.Type == "sid");

                tokenStore.SaveSid(sid.Value);
                tokenStore.SaveUserDetails(userDetails);
                notification.HandleCodeRedemption(null, result.IdToken);
            }
            catch (MsalException ex)
            {
                string message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
            catch (Microsoft.Graph.ServiceException ex)
            {
                string message = "GetUserDetailsAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
        }
コード例 #8
0
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification)
        {
            // Get the signed in user's id and create a token cache
            string            signedInUserId = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            SessionTokenStore tokenStore     = new SessionTokenStore(signedInUserId,
                                                                     notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase);

            var idClient = new ConfidentialClientApplication(
                appId, redirectUri, new ClientCredential(appSecret), tokenStore.GetMsalCacheInstance(), null);

            try
            {
                string[] scopes = graphScopes.Split(' ');

                var result = await idClient.AcquireTokenByAuthorizationCodeAsync(
                    notification.Code, scopes);

                var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken);

                var cachedUser = new CachedUser()
                {
                    DisplayName = userDetails.DisplayName,
                    Email       = string.IsNullOrEmpty(userDetails.Mail) ?
                                  userDetails.UserPrincipalName : userDetails.Mail,
                    Avatar      = string.Empty,
                    AccessToken = result.AccessToken
                };

                tokenStore.SaveUserDetails(cachedUser);
            }
            catch (MsalException ex)
            {
                string message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
            catch (Microsoft.Graph.ServiceException ex)
            {
                string message = "GetUserDetailsAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
        }
コード例 #9
0
        // If the javascript issues an OIDC authorize reuest, and it succeeds, the user is already logged
        // into AAD.  Since the AAD session cookie has changed, we need to check if the same use is still
        // logged in.
        public static Task AuthorizationCodeRecieved(AuthorizationCodeReceivedNotification notification)
        {
            // If the successful authorize request was issued by the SingleSignOut javascript
            if (notification.AuthenticationTicket.Properties.RedirectUri.Contains("SessionChanged"))
            {
                // Clear the SingleSignOut Cookie
                ICookieManager       cookieManager = new ChunkingCookieManager();
                string               cookie        = cookieManager.GetRequestCookie(notification.OwinContext, CookieName);
                AuthenticationTicket ticket        = ticketDataFormat.Unprotect(cookie);
                if (ticket.Properties.Dictionary != null)
                {
                    ticket.Properties.Dictionary[OpenIdConnectAuthenticationDefaults.AuthenticationType + "SingleSignOut"] = "";
                }
                cookieManager.AppendResponseCookie(notification.OwinContext, CookieName, ticketDataFormat.Protect(ticket), new CookieOptions());

                Claim existingUserObjectId = notification.OwinContext.Authentication.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");
                Claim incomingUserObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");

                if (existingUserObjectId.Value != null && incomingUserObjectId != null)
                {
                    // If a different user is logged into AAD
                    if (existingUserObjectId.Value != incomingUserObjectId.Value)
                    {
                        // No need to clear the session state here. It has already been
                        // updated with the new user's session state in SecurityTokenValidated.
                        notification.Response.Redirect("Account/SingleSignOut");
                        notification.HandleResponse();
                    }
                    // If the same user is logged into AAD
                    else if (existingUserObjectId.Value == incomingUserObjectId.Value)
                    {
                        // No need to clear the session state, SecurityTokenValidated will do so.
                        // Simply redirect the iframe to a page other than SingleSignOut to reset
                        // the timer in the javascript.
                        notification.Response.Redirect("/");
                        notification.HandleResponse();
                    }
                }
            }

            return(Task.FromResult <object>(null));
        }
コード例 #10
0
        private static async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification)
        {
            //IConfidentialClientApplication clientApp = MsalAppBuilder.
            notification.HandleCodeRedemption();

            var idClient = ConfidentialClientApplicationBuilder.Create(appId)
                           .WithRedirectUri(redirectUri)
                           .WithClientSecret(appSecret)
                           .Build();

            var signedInUser = new ClaimsPrincipal(notification.AuthenticationTicket.Identity);
            var tokenStore   = new SessionTokenStore(idClient.UserTokenCache, HttpContext.Current, signedInUser);

            try
            {
                string[] scopes = graphScopes.Split(' ');

                var result = await idClient.AcquireTokenByAuthorizationCode(
                    scopes, notification.Code).ExecuteAsync();

                //var userMessage = await GraphHelper.GetMeAsync(result.AccessToken);
                //var userSend = await GraphHelper.SendMailAsync(result.AccessToken);
                //var userDetails = await OutlookFW.Web.Controllers.MailController._mailAppService.GetUserDetailsAsync(result.AccessToken);
                //email= userDetails.Email.ToString();
                accessToken = result.AccessToken;
                //tokenStore.SaveUserDetails(userDetails);
                notification.HandleCodeRedemption(null, result.IdToken);
            }
            catch (MsalException ex)
            {
                string message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
            catch (Microsoft.Graph.ServiceException ex)
            {
                string message = "GetUserDetailsAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
        }
コード例 #11
0
 private static void HandlePolicyViolation(AuthorizationCodeReceivedNotification notification, ServerException ex)
 {
     if (ex.Status == HttpStatusCode.NotAcceptable)
     {
         notification.Response.Redirect(ex.GetErrorData <ValidationError>().Url);
         notification.HandleResponse();
     }
     else
     {
         _debugLogger?.Invoke(ex.ErrorData);
         _debugLogger?.Invoke(ex.Message);
         _exceptionLogger?.Invoke(ex);
         notification.OwinContext.Authentication.SignIn(notification.AuthenticationTicket.Identity);
     }
 }
コード例 #12
0
        /*
         * Callback function when an authorization code is received
         */
        private static async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification, TokenProviderConfiguration configuration)
        {
            var ct = HttpContext.Current;

            try
            {
                if (IsMfaRequired(notification, configuration) && !notification.AuthenticationTicket.Identity.Claims.Any(c => c.Type == "mfa_required" && c.Value == "true"))
                {
                    throw new UnauthorizedAccessException("MFA required");
                }
                await ExchangeAuthCodeWithToken(notification, configuration);

                try
                {
                    await ValidatePolicies(notification);

                    notification.OwinContext.Authentication.SignIn(notification.AuthenticationTicket.Identity);
                    notification.Response.Redirect(notification.RedirectUri);
                    notification.HandleResponse();
                    HttpContext.Current = ct;
                }
                catch (AggregateException aex)
                {
                    _exceptionLogger?.Invoke(aex);
                    if (aex.InnerException != null)
                    {
                        _exceptionLogger?.Invoke(aex.InnerException);
                    }
                    HttpContext.Current = ct;
                    if (aex.InnerException is ServerException serverException)
                    {
                        HandlePolicyViolation(notification, serverException);
                    }
                }
                catch (ServerException ex)
                {
                    _exceptionLogger?.Invoke(ex);
                    HttpContext.Current = ct;
                    HandlePolicyViolation(notification, ex);
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current = ct;
                _exceptionLogger?.Invoke(ex);
                throw;
            }
        }
コード例 #13
0
        //private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification)
        //{
        //    // Get the signed in user's id and create a token cache
        //    string signedInUserId = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
        //    SessionTokenStore tokenStore = new SessionTokenStore(signedInUserId,
        //        notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase);

        //    var idClient = new ConfidentialClientApplication(
        //        appId, redirectUri, new ClientCredential(appSecret), tokenStore.GetMsalCacheInstance(), null);

        //    try
        //    {
        //        string[] scopes = graphScopes.Split(' ');

        //        var result = await idClient.AcquireTokenByAuthorizationCodeAsync(
        //            notification.Code, scopes);

        //        var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken);

        //        var cachedUser = new CachedUser()
        //        {
        //            DisplayName = userDetails.DisplayName,
        //            Email = string.IsNullOrEmpty(userDetails.Mail) ?
        //            userDetails.UserPrincipalName : userDetails.Mail,
        //            Avatar = string.Empty
        //        };

        //        tokenStore.SaveUserDetails(cachedUser);
        //    }
        //    catch (MsalException ex)
        //    {
        //        string message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
        //        notification.HandleResponse();
        //        notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
        //    }
        //    catch (Microsoft.Graph.ServiceException ex)
        //    {
        //        string message = "GetUserDetailsAsync threw an exception";
        //        notification.HandleResponse();
        //        notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
        //    }
        //}

        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification)
        {
            var idClient = new ConfidentialClientApplication(
                appId, redirectUri, new ClientCredential(appSecret), null, null);

            string message;
            string debug;

            try
            {
                string[] scopes = graphScopes.Split(' ');

                var result = await idClient.AcquireTokenByAuthorizationCodeAsync(
                    notification.Code, scopes);

                var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken);

                string email = string.IsNullOrEmpty(userDetails.Mail) ?
                               userDetails.UserPrincipalName : userDetails.Mail;

                message = "User info retrieved.";
                debug   = $"User: {userDetails.DisplayName}, Email: {email}";
            }
            //try
            //{
            //    string[] scopes = graphScopes.Split(' ');

            //    var result = await idClient.AcquireTokenByAuthorizationCodeAsync(
            //        notification.Code, scopes);

            //    message = "Access token retrieved.";
            //    debug = result.AccessToken;
            //}
            catch (MsalException ex)
            {
                message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
                debug   = ex.Message;
            }

            notification.HandleResponse();
            notification.Response.Redirect($"/Home/Error?message={message}&debug={debug}");
        }
コード例 #14
0
        private static async Task ValidatePolicies(AuthorizationCodeReceivedNotification notification)
        {
            _debugLogger?.Invoke($"Validating policies with api: {VeracityApiUrl}");
            var validator = ServiceProviderFactory?.Invoke()?.GetService(typeof(IPolicyValidation)) as IPolicyValidation;

            if (validator != null)
            {
                var policy = ConfigurationManagerHelper.GetValueOnKey("serviceId").ContainsCharacters()
                    ? await validator.ValidatePolicyWithServiceSpesificTerms(ConfigurationManagerHelper.GetValueOnKey("serviceId"), notification.RedirectUri)
                    : await validator.ValidatePolicy(notification.RedirectUri ?? _redirectUrl);

                if (!policy.AllPoliciesValid)
                {
                    _debugLogger?.Invoke($"policies validated, redirecting to {policy.RedirectUrl} for approval");
                    notification.Response.Redirect(policy.RedirectUrl);
                    notification.HandleResponse();
                    return;
                }
            }
            _debugLogger?.Invoke($"policies validated");
        }
コード例 #15
0
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            // Get the signed in user's id and create a token cache
            string            signedInUserId = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            SessionTokenCache tokenCache     = new SessionTokenCache(signedInUserId,
                                                                     notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase);

            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                appId, redirectUri, new ClientCredential(appSecret), tokenCache);

            try
            {
                string[] scopes = { "User.Read", "Mail.Send" };
                var      result = await cca.AcquireTokenByAuthorizationCodeAsync(scopes, notification.Code);
            }
            catch (MsalException ex)
            {
                string message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect("/Error?message=" + message + "&debug=" + ex.Message);
            }
        }
コード例 #16
0
        public async Task HandleOpenIdAuthorizationCodeAsync(
            AuthorizationCodeReceivedNotification authorizationCodeReceived)
        {
            string tokenAsBase64 =
                JwtTokenHelper.CreateSecurityTokenDescriptor(authorizationCodeReceived.JwtSecurityToken.Claims,
                                                             _jwtOptions).CreateTokenAsBase64();

            authorizationCodeReceived.AuthenticationTicket.Properties.RedirectUri +=
                string.Format("&{0}={1}", _jwtOptions.JwtTokenParameterName, tokenAsBase64);

            if (_createConsentOptions.CreateConsentAsync != null)
            {
                await _createConsentOptions.CreateConsentAsync(authorizationCodeReceived.Response,
                                                               new Uri(authorizationCodeReceived.AuthenticationTicket.Properties.RedirectUri));

                authorizationCodeReceived.HandleResponse();
            }
            else
            {
                string implicitConsent = string.Format("&{0}={1}", _consentHandlerOptions.ConsentParameterName,
                                                       Uri.EscapeDataString("implicit"));
                authorizationCodeReceived.AuthenticationTicket.Properties.RedirectUri += implicitConsent;
            }
        }
コード例 #17
0
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification)
        {
            var idClient = ConfidentialClientApplicationBuilder.Create(appId)
                           .WithRedirectUri(redirectUri)
                           .WithClientSecret(appSecret)
                           .Build();

            var signedInUser = new ClaimsPrincipal(notification.AuthenticationTicket.Identity);
            var tokenStore   = new SessionTokenStore(idClient.UserTokenCache, HttpContext.Current, signedInUser);

            try
            {
                string[] scopes = graphScopes.Split(' ');

                var result = await idClient.AcquireTokenByAuthorizationCode(
                    scopes, notification.Code).ExecuteAsync();

                var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken);

                string profilePhoto;

                try
                {
                    var photo = await GraphHelper.GetUserPhotoAsync(result.AccessToken);

                    if (photo != null)
                    {
                        profilePhoto = "data:image/png;base64, " + Convert.ToBase64String(photo);
                    }
                    else
                    {
                        profilePhoto = null;
                    }
                }
                catch
                {
                    profilePhoto = null;
                }

                var cachedUser = new CachedUser()
                {
                    DisplayName = userDetails.DisplayName,
                    Email       = userDetails.UserPrincipalName,
                    TenantID    = result.TenantId,
                    Avatar      = profilePhoto
                };

                tokenStore.SaveUserDetails(cachedUser);
            }
            catch (MsalException ex)
            {
                string message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
            catch (Microsoft.Graph.ServiceException ex)
            {
                string message = "GetUserDetailsAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
        }
コード例 #18
0
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification)
        {
            var idClient = ConfidentialClientApplicationBuilder.Create(appId)
                           .WithRedirectUri(redirectUri)
                           .WithClientSecret(appSecret)
                           .Build();

            string message;
            var    signedInUser = new ClaimsPrincipal(notification.AuthenticationTicket.Identity);
            var    tokenStore   = new SessionStore(idClient.UserTokenCache, HttpContext.Current, signedInUser);

            try
            {
                string[] scopes = graphScopes.Split(' ');

                var result = await idClient.AcquireTokenByAuthorizationCode(
                    scopes, notification.Code).ExecuteAsync();

                var graphClient = new GraphServiceClient(
                    new DelegateAuthenticationProvider(
                        async(requestMessage) =>
                {
                    requestMessage.Headers.Authorization =
                        new AuthenticationHeaderValue("Bearer", result.AccessToken);
                }));
                HttpCookie myCookie = new HttpCookie("myCookie");
                myCookie.Domain = ".MailBoxIntegration.com";
                //Add key-values in the cookie
                //myCookie.Values.Add("userid", result.AccessToken);
                myCookie.Value = result.AccessToken;
                //set cookie expiry date-time. Made it to last for next 12 hours.
                myCookie.Expires = DateTime.Now.AddHours(12);

                //Most important, write the cookie to client.
                HttpContext.Current.Response.Cookies.Add(myCookie);

                //HttpCookie chk = new HttpCookie("chk");
                //chk.Domain = ".MailBoxIntegration.com";
                //chk.Name = "Token";
                //chk.Value = result.AccessToken;
                var userDetails = await graphClient.Me.Request().GetAsync();

                //var userDetails = await GraphHelper.GetUserDetailsAsync(result.AccessToken);

                var cachedUser = new CachedUser()
                {
                    DisplayName = userDetails.DisplayName,
                    Email       = (string.IsNullOrEmpty(userDetails.Mail) ? userDetails.UserPrincipalName : userDetails.Mail),
                    Avatar      = string.Empty
                };

                tokenStore.SaveUserDetails(cachedUser);
            }
            catch (MsalException ex)
            {
                message = "AcquireTokenByAuthorizationCodeAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
            catch (Microsoft.Graph.ServiceException ex)
            {
                message = "GetUserDetailsAsync threw an exception";
                notification.HandleResponse();
                notification.Response.Redirect($"/Home/Error?message={message}&debug={ex.Message}");
            }
        }
コード例 #19
0
        // If the javascript issues an OIDC authorize reuest, and it succeeds, the user is already logged
        // into AAD.  Since the AAD session cookie has changed, we need to check if the same use is still
        // logged in.
        public static Task AuthorizationCodeRecieved(AuthorizationCodeReceivedNotification notification)
        {
            // If the successful authorize request was issued by the SingleSignOut javascript
            if (notification.AuthenticationTicket.Properties.RedirectUri.Contains("SessionChanged")) 
            {
                // Clear the SingleSignOut Cookie
                ICookieManager cookieManager = new ChunkingCookieManager();
                string cookie = cookieManager.GetRequestCookie(notification.OwinContext, CookieName);
                AuthenticationTicket ticket = ticketDataFormat.Unprotect(cookie);
                if (ticket.Properties.Dictionary != null)
                    ticket.Properties.Dictionary[OpenIdConnectAuthenticationDefaults.AuthenticationType + "SingleSignOut"] = "";
                cookieManager.AppendResponseCookie(notification.OwinContext, CookieName, ticketDataFormat.Protect(ticket), new CookieOptions());

                Claim existingUserObjectId = notification.OwinContext.Authentication.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");
                Claim incomingUserObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");

                if (existingUserObjectId.Value != null && incomingUserObjectId != null)
                {   
                    // If a different user is logged into AAD
                    if(existingUserObjectId.Value != incomingUserObjectId.Value)
                    {
                        // No need to clear the session state here. It has already been
                        // updated with the new user's session state in SecurityTokenValidated.
                        notification.Response.Redirect("Account/SingleSignOut");
                        notification.HandleResponse();            
                    }
                    // If the same user is logged into AAD
                    else if (existingUserObjectId.Value == incomingUserObjectId.Value)
                    {
                        // No need to clear the session state, SecurityTokenValidated will do so.
                        // Simply redirect the iframe to a page other than SingleSignOut to reset
                        // the timer in the javascript.
                        notification.Response.Redirect("/");
                        notification.HandleResponse();
                    }
                }
            }
            
            return Task.FromResult<object>(null);
        }