コード例 #1
0
        public static async Task setTokenAsync(AuthorizationCodeReceivedNotification context)
        {
            var code = context.Code;
            ClientCredential      credential   = new ClientCredential(AuthConstants.CLIENT_ID, AuthConstants.APP_KEY);
            string                userObjectID = context.AuthenticationTicket.Identity.FindFirst(AuthConstants.claimIdentifier).Value;
            AuthenticationContext authContext  = new AuthenticationContext(AuthConstants.AUTHORITY, true);

            Uri uri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
            AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, uri, credential, AuthConstants.powerBIResourceId);

            string AccessToken = result.AccessToken;

            HttpCookie myCookie = new HttpCookie(AuthConstants.accessCookie);

            // Set the cookie value.
            myCookie.Value = AccessToken;
            // Set the cookie expiration date time.
            DateTime now = DateTime.Now;

            myCookie.Expires = now.AddMinutes(58);
            // Add the cookie.
            HttpContext.Current.Response.Cookies.Add(myCookie);

            HttpContext.Current.Session.Add(AuthConstants.accessToken, AccessToken);
            // Set the session expiration time
            HttpContext.Current.Session.Timeout = 58; //minutes
        }
        private async Task <AuthorizationCodeReceivedNotification> RunAuthorizationCodeReceivedNotificationAsync(OpenIdConnectMessage message, AuthenticationProperties properties, AuthenticationTicket ticket, JwtSecurityToken jwt)
        {
            var redirectUri = properties.Items.ContainsKey(OpenIdConnectAuthenticationDefaults.RedirectUriForCodePropertiesKey) ?
                              properties.Items[OpenIdConnectAuthenticationDefaults.RedirectUriForCodePropertiesKey] : Options.RedirectUri;

            Logger.LogDebug(Resources.OIDCH_0014_AuthorizationCodeReceived, message.Code);

            var authorizationCodeReceivedNotification = new AuthorizationCodeReceivedNotification(Context, Options)
            {
                Code                 = message.Code,
                ProtocolMessage      = message,
                RedirectUri          = redirectUri,
                AuthenticationTicket = ticket,
                JwtSecurityToken     = jwt
            };

            await Options.Notifications.AuthorizationCodeReceived(authorizationCodeReceivedNotification);

            if (authorizationCodeReceivedNotification.HandledResponse)
            {
                Logger.LogVerbose(Resources.OIDCH_0015_AuthorizationCodeReceivedNotificationHandledResponse);
            }
            else if (authorizationCodeReceivedNotification.Skipped)
            {
                Logger.LogVerbose(Resources.OIDCH_0016_AuthorizationCodeReceivedNotificationSkipped);
            }

            return(authorizationCodeReceivedNotification);
        }
コード例 #3
0
        private async Task OnAuthorizationCodeReceived(
            AuthorizationCodeReceivedNotification context)
        {
            var user = new ClaimsPrincipal(context.AuthenticationTicket.Identity);

            var telemetryContext = new TelemetryContext
            {
                TenantId     = user.GetTenantId(),
                UserObjectId = user.GetUserObjectId()
            };

            TelemetryHelper.LogVerbose(@"OnAuthorizationCodeReceived", telemetryContext);

            var authContext = new AuthenticationContext($"{ConfigHelper.AuthenticationEndpoint}{user.GetTenantId()}");
            var result      = await authContext.AcquireTokenByAuthorizationCodeAsync(
                context.Code,
                new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)),
                new ClientCredential(ConfigHelper.ApplicationId, ConfigHelper.ApplicationSecret),
                ConfigHelper.ResourceManagerEndpoint);

            context.AuthenticationTicket.Identity.AddClaims(new[]
            {
                new Claim(Constants.TokenKey, result.AccessToken)
            });

            TelemetryHelper.WriteEvent(
                TelemetryEventNames.AuthSignedIn,
                telemetryContext);
        }
コード例 #4
0
        private static async Task AuthorizationCodeReceived(AuthorizationCodeReceivedNotification n, string authority, string clientId, string clientSecret)
        {
            var tokenEndpoint = $"{authority}/connect/token";

            if (n.Code != null)
            {
                // use the code to get the access and refresh token
                var tokenResponse = await StsTokenHelper.RequestToken(_client, tokenEndpoint, clientId, clientSecret, n.Code, n.RedirectUri);

                // create new identity
                //var claimsIdent = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType);
                var claimsIdent = n.AuthenticationTicket.Identity;

                bool includeUserClaims = claimsIdent.FindFirst("role") == null;
                if (includeUserClaims)
                {
                    //Add userClaims from userInfoEndpoint with the access token
                    await AddUserClaimsAsync(claimsIdent, authority, tokenResponse.AccessToken);


                    //Add portal
                    //AddPortalGroupInfo(claimsIdent);
                }

                claimsIdent.AddOrUpdateClaim("access_token", tokenResponse.AccessToken);
                claimsIdent.AddOrUpdateClaim("expires_at", tokenResponse.ExpiresUtc().ToString());
                claimsIdent.AddOrUpdateClaim("refresh_token", tokenResponse.RefreshToken);
                claimsIdent.AddOrUpdateClaim("id_token", n.ProtocolMessage.IdToken);

                n.AuthenticationTicket.Properties.ExpiresUtc = tokenResponse.ExpiresUtc();
            }
        }
        public async Task ThrowsOnInvalidTokenResponse()
        {
            var httpClient = A.Fake <HttpClient>();

            A.CallTo(() => httpClient.SendAsync(A <ProtocolRequest> ._, A <CancellationToken> ._))
            .Returns(new HttpResponseMessage
            {
                Content = new StringContent(
                    "xxxxxxxxxxxxxxxxx")
            });

            var notifications = new VippsOpenIdConnectAuthenticationNotifications(httpClient);

            var configurationManager =
                A.Fake <IConfigurationManager <OpenIdConnectConfiguration> >();

            A.CallTo(() => configurationManager.GetConfigurationAsync(A <CancellationToken> ._))
            .Returns(new OpenIdConnectConfiguration());

            var notification = new AuthorizationCodeReceivedNotification(
                A.Fake <IOwinContext>(),
                new VippsOpenIdConnectAuthenticationOptions("clientId", "clientSecret", "authority")
            {
                ConfigurationManager = configurationManager
            })
            {
                RedirectUri = "https://redirect-url",
                Code        = "AuthCode"
            };
            await Assert.ThrowsAsync <OpenIdConnectProtocolException>(async() =>
                                                                      await notifications.AuthorizationCodeReceived(notification));
        }
        public async Task RetrievesTokenEndpointResponse()
        {
            var httpClient = A.Fake <HttpClient>();

            A.CallTo(() => httpClient.SendAsync(A <ProtocolRequest> ._, A <CancellationToken> ._))
            .Returns(new HttpResponseMessage
            {
                Content = new StringContent(
                    "{\"access_token\":\"abcde\",\"expires_in\":3599,\"id_token\":\"qwerty\",\"scope\":\"phoneNumber address email name openid birthDate\",\"token_type\":\"bearer\"}")
            });

            var notifications = new VippsOpenIdConnectAuthenticationNotifications(httpClient);

            var configurationManager =
                A.Fake <IConfigurationManager <OpenIdConnectConfiguration> >();

            A.CallTo(() => configurationManager.GetConfigurationAsync(A <CancellationToken> ._))
            .Returns(new OpenIdConnectConfiguration());

            var notification = new AuthorizationCodeReceivedNotification(
                A.Fake <IOwinContext>(),
                new VippsOpenIdConnectAuthenticationOptions("clientId", "clientSecret", "authority")
            {
                ConfigurationManager = configurationManager
            })
            {
                RedirectUri = "https://redirect-url",
                Code        = "AuthCode"
            };
            await notifications.AuthorizationCodeReceived(notification);

            Assert.Equal("abcde", notification.TokenEndpointResponse.AccessToken);
            Assert.Equal("qwerty", notification.TokenEndpointResponse.IdToken);
        }
コード例 #7
0
ファイル: TokenExchanger.cs プロジェクト: madmagi/okta-aspnet
        public async Task ExchangeCodeForTokenAsync(AuthorizationCodeReceivedNotification response)
        {
            var openIdConfiguration = await _configurationManager.GetConfigurationAsync().ConfigureAwait(false);

            var tokenResponse = await _httpClient.RequestAuthorizationCodeTokenAsync(new AuthorizationCodeTokenRequest
            {
                Address      = openIdConfiguration.TokenEndpoint,
                ClientId     = _options.ClientId,
                ClientSecret = _options.ClientSecret,
                Code         = response.Code,
                RedirectUri  = _options.RedirectUri,
            }).ConfigureAwait(false);

            if (tokenResponse.IsError)
            {
                throw new Exception(tokenResponse.Error);
            }

            FillNameIdentifierClaimOnIdentity(response.AuthenticationTicket.Identity);

            response.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", tokenResponse.IdentityToken));
            response.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", tokenResponse.AccessToken));

            if (!string.IsNullOrEmpty(tokenResponse.RefreshToken))
            {
                response.AuthenticationTicket.Identity.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
            }

            return;
        }
コード例 #8
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}");
            }
        }
コード例 #9
0
ファイル: Startup.Auth.cs プロジェクト: dz1986/ssi204
        // Redeem code for token asynchronosly for performance, must not do synchronous call for Production
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            Startup.LastContext = context;
            code      = context.Code;
            returnUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));

            // Token Service appKey is required to authenticate with Azure AD for redeeming the authorization code
            // Note that the code is returned to LE-SfBApp, but the JavaScript client cannot make use of it
            ClientCredential credential = new ClientCredential(clientId, appKey);

            // userObjectID is the objectGUID of the O365 user in Azure AD
            string userObjectID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            // intialize with common to retrieve MRRT, index Cache with both user GUID and resource url due to UCWA usage pattern
            // Startup.sessionCache = new NaiveSessionCache(userObjectID);
            // Startup.sessionCache = new NaiveSessionCache(userObjectID);
            // Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(Startup.Authority, Startup.sessionCache);
            AuthContext authContext = new AuthContext(Authority,
                                                      new DistributedTokenCache(cacheconnStr, userObjectID));

            AuthenticationResult result = await authContext.AcquireTokenByAuthorizationCodeAsync(code, returnUri, credential, ucwaResourceUrl);

            // Azure AD schema change
            // string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            // string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            // AuthenticationContext authContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));

            Startup.accessToken  = result.AccessToken;
            Startup.refreshToken = result.RefreshToken;
            Startup.idToken      = result.IdToken;
        }
        // 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));
        }
コード例 #11
0
 private async Task OnAuthorizationCodeRecieved(AuthorizationCodeReceivedNotification context)
 {
     // Upon successful sign in, get & cache a token using MSAL
     string userId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
     ConfidentialClientApplication cc     = new ConfidentialClientApplication(Globals.ClientId, Globals.RedirectUri, new ClientCredential(Globals.ClientSecret), new MsalSessionTokenCache(userId, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase));
     AuthenticationResult          result = await cc.AcquireTokenByAuthorizationCodeAsync(new[] { "user.readbasic.all" }, context.Code);
 }
コード例 #12
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;
            }

        }
コード例 #13
0
ファイル: Startup.Auth.cs プロジェクト: Benjlr/Simplify
        /*
         * Callback function when an authorization code is received
         */
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            try
            {
                /*
                 * The `MSALPerUserMemoryTokenCache` is created and hooked in the `UserTokenCache` used by `IConfidentialClientApplication`.
                 * At this point, if you inspect `ClaimsPrinciple.Current` you will notice that the Identity is still unauthenticated and it has no claims,
                 * but `MSALPerUserMemoryTokenCache` needs the claims to work properly. Because of this sync problem, we are using the constructor that
                 * receives `ClaimsPrincipal` as argument and we are getting the claims from the object `AuthorizationCodeReceivedNotification context`.
                 * This object contains the property `AuthenticationTicket.Identity`, which is a `ClaimsIdentity`, created from the token received from
                 * Azure AD and has a full set of claims.
                 */
                IConfidentialClientApplication confidentialClient = MsalAppBuilder.BuildConfidentialClientApplication(new ClaimsPrincipal(notification.AuthenticationTicket.Identity));

                // Upon successful sign in, get & cache a token using MSAL
                AuthenticationResult result = await confidentialClient.AcquireTokenByAuthorizationCode(Globals.Scopes, notification.Code).ExecuteAsync();
            }
            catch (Exception ex)
            {
                throw new HttpResponseException(new HttpResponseMessage
                {
                    StatusCode   = HttpStatusCode.BadRequest,
                    ReasonPhrase = $"Unable to get authorization code {ex.Message}."
                });
            }
        }
コード例 #14
0
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            // Upon successful sign in, get the access token & cache it using MSAL
            IConfidentialClientApplication clientApp = await MsalAppBuilder.BuildConfidentialClientApplication();

            AuthenticationResult result = await clientApp.AcquireTokenByAuthorizationCode(new[] { "Mail.Read" }, context.Code).ExecuteAsync();
        }
コード例 #15
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);
            }
        }
コード例 #16
0
        /// <summary>
        /// Retrieve the code_verifier from authentication process
        /// </summary>
        public static string RetrieveCodeVerifier(this AuthorizationCodeReceivedNotification n)
        {
            // retreive the cookie key
            string key = GetCodeVerifierKey(n.ProtocolMessage.State);

            // retrive the cookie value by key
            string codeVerifierCookie = n.Options.CookieManager.GetRequestCookie(n.OwinContext, key);

            if (codeVerifierCookie != null)
            {
                // delete the cookie from authentication process
                var cookieOptions = new CookieOptions
                {
                    SameSite = SameSiteMode.None,
                    HttpOnly = true,
                    Secure   = n.Request.IsSecure
                };

                n.Options.CookieManager.DeleteCookie(n.OwinContext, key, cookieOptions);
            }

            // read the AuthenticationProperties from the authentication session
            var cookieProperties = n.Options.StateDataFormat.Unprotect(Encoding.UTF8.GetString(Convert.FromBase64String(codeVerifierCookie)));

            // retrive the code_verifier value
            cookieProperties.Dictionary.TryGetValue("cv", out var codeVerifier);

            return(codeVerifier);
        }
コード例 #17
0
ファイル: Startup.Auth.cs プロジェクト: nianton/AADB2C-WebAPI
        /*
         * Callback function when an authorization code is received
         */
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            // Extract the code from the response notification
            string code = notification.Code;

            // Extract signed in user id
            string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

            // MSAL v3 confidential application creation
            IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(ClientId)
                                                 .WithB2CAuthority(Authority)
                                                 .WithClientSecret(ClientSecret)
                                                 .WithRedirectUri(RedirectUri)
                                                 .Build();

            // Enable encrypted persistence to local file for tokens
            TokenCacheHelper.EnableSerialization(cca.UserTokenCache);

            try
            {
                // MSAL v3 get accesstoken by authorization code
                AuthenticationResult result = await cca.AcquireTokenByAuthorizationCode(Scopes, code).ExecuteAsync();
            }
            catch (Exception ex)
            {
                //TODO: Handle
                throw;
            }
        }
コード例 #18
0
        private async Task ProcessAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            // Exchange code for access and ID tokens
            var tokenClient   = new TokenClient(Authority + OauthTokenEndpoint, ClientId, ClientSecret);
            var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(notification.Code, notification.RedirectUri);

            if (tokenResponse.IsError)
            {
                throw new Exception(tokenResponse.Error);
            }

            var userInfoClient   = new UserInfoClient(Authority + OauthUserInfoEndpoint);
            var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken);

            var claims = new List <Claim>();

            claims.AddRange(userInfoResponse.Claims);
            claims.Add(new Claim("id_token", tokenResponse.IdentityToken));
            claims.Add(new Claim("access_token", tokenResponse.AccessToken));

            if (!string.IsNullOrEmpty(tokenResponse.RefreshToken))
            {
                claims.Add(new Claim("refresh_token", tokenResponse.RefreshToken));
            }

            notification.AuthenticationTicket.Identity.AddClaims(claims);
            notification.AuthenticationTicket.Identity.ApplyClaimsTransformations(new TransformationContext(this.FederatedAuthenticationConfiguration, IdentityProvider));
        }
コード例 #19
0
        public async Task ExchangeCodeForTokenAsync(AuthorizationCodeReceivedNotification response)
        {
            var openIdConfiguration = await _configurationManager.GetConfigurationAsync().ConfigureAwait(false);

            var tokenClient   = new TokenClient(openIdConfiguration.TokenEndpoint, _options.ClientId, _options.ClientSecret);
            var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(response.Code, _options.RedirectUri).ConfigureAwait(false);

            if (tokenResponse.IsError)
            {
                throw new Exception(tokenResponse.Error);
            }

            if (_options.GetClaimsFromUserInfoEndpoint)
            {
                await EnrichIdentityViaUserInfoAsync(
                    response.AuthenticationTicket.Identity,
                    openIdConfiguration,
                    tokenResponse).ConfigureAwait(false);
            }

            response.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", tokenResponse.IdentityToken));
            response.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", tokenResponse.AccessToken));

            if (!string.IsNullOrEmpty(tokenResponse.RefreshToken))
            {
                response.AuthenticationTicket.Identity.AddClaim(new Claim("refresh_token", tokenResponse.RefreshToken));
            }

            return;
        }
コード例 #20
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));
        }
コード例 #21
0
        internal static async Task AuthInit(AuthorizationCodeReceivedNotification ctx)
        {
            var hctx =
                (HttpContextWrapper)
                ctx.OwinContext.Environment.Single(e => e.Key == "System.Web.HttpContextBase").Value;

            await AuthInit(hctx, (ClaimsIdentity)ctx.Request.User.Identity);
        }
コード例 #22
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            if (Options.CallbackPath.HasValue && Options.CallbackPath != Request.PathBase + Request.Path)
            {
                return(null);
            }

            var state = Request.Query.Get("state");
            var error = Request.Query.Get("error");
            var code  = Request.Query.Get("code");
            var openIdConnectMessage = new OpenIdConnectMessage
            {
                Error = error,
                State = state,
                Code  = code,
            };

            ExceptionDispatchInfo authFailedEx;

            try
            {
                var properties = GetPropertiesFromState(state);
                if (properties == null)
                {
                    log.Warn("The state field is missing or invalid.");
                    return(null);
                }
                if (!string.IsNullOrWhiteSpace(openIdConnectMessage.Error))
                {
                    throw new OpenIdConnectProtocolException(
                              string.Format(CultureInfo.InvariantCulture, openIdConnectMessage.Error, typeof(Exception), openIdConnectMessage.ErrorDescription ?? string.Empty, openIdConnectMessage.ErrorUri ?? string.Empty));
                }

                if (openIdConnectMessage.Code != null)
                {
                    var authorizationCodeReceivedNotification = new AuthorizationCodeReceivedNotification(Context, Options)
                    {
                        Code            = openIdConnectMessage.Code,
                        ProtocolMessage = openIdConnectMessage,
                        RedirectUri     = properties.Dictionary.ContainsKey("OpenIdConnect.Code.RedirectUri") ? properties.Dictionary["OpenIdConnect.Code.RedirectUri"] : string.Empty
                    };
                    await Options.Notifications.AuthorizationCodeReceived(authorizationCodeReceivedNotification);
                }
                var identity = new ClaimsIdentity();
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, code));
                return(new AuthenticationTicket(identity, properties));
            }
            catch (Exception ex)
            {
                authFailedEx = ExceptionDispatchInfo.Capture(ex);
            }
            if (authFailedEx != null)
            {
                log.Error("Exception occurred while processing message: ", authFailedEx.SourceException);
                authFailedEx.Throw();
            }
            return(null);
        }
コード例 #23
0
        /*
         * Callback function when an authorization code is received
         */
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            //AD B2C token will be received here after authentication. The token will have role claims which will be added in the AuthenticationTicket.Identity automatically.


            //try
            //{
            //    IConfidentialClientApplication confidentialClient = MsalAppBuilder.BuildConfidentialClientApplication(new ClaimsPrincipal(notification.AuthenticationTicket.Identity));

            //    // Upon successful sign in, get & cache a token using MSAL
            //    //AuthenticationResult result = await confidentialClient.AcquireTokenByAuthorizationCode(Globals.Scopes, notification.Code).ExecuteAsync();
            //    //string token = result.AccessToken;

            //    using (var client = new HttpClient())
            //    {

            //        string tokenURL = "https://login.microsoftonline.com/rallycommunitas.onmicrosoft.com/oauth2/v2.0/token";

            //        var requestContent = new FormUrlEncodedContent(new[]
            //        {
            //            new KeyValuePair<string, string>("grant_type", "client_credentials"),
            //            new KeyValuePair<string, string>("client_id", Globals.RoleClientId),
            //            new KeyValuePair<string, string>("scope", "https://graph.microsoft.com/.default"),
            //            new KeyValuePair<string, string>("client_secret", Globals.RoleClientSecret)
            //        });


            //        var response1 = await client.PostAsync(tokenURL, requestContent);
            //        var responseContent = await response1.Content.ReadAsStringAsync();

            //        var tokenObj = JObject.Parse(responseContent);
            //        JToken accessToke = tokenObj.GetValue("access_token");
            //        string accessToken = tokenObj.GetValue("access_token").Value<string>();

            //        string requestUrl = $"https://graph.microsoft.com/v1.0/users/{notification.JwtSecurityToken.Subject}/memberOf?$select=displayName";

            //        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
            //        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

            //        HttpResponseMessage response = await client.SendAsync(request);
            //        var responseString = await response.Content.ReadAsStringAsync();

            //        var json = JObject.Parse(responseString);

            //        foreach (var group in json["value"])
            //            notification.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, group["displayName"].ToString(), System.Security.Claims.ClaimValueTypes.String, "Graph"));
            //    }

            //}
            //catch (Exception ex)
            //{
            //    throw new HttpResponseException(new HttpResponseMessage
            //    {
            //        StatusCode = HttpStatusCode.BadRequest,
            //        ReasonPhrase = $"Unable to get authorization code {ex.Message}."
            //    });
            //}
        }
コード例 #24
0
 public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
 {
     // Acquire a Token for the Graph API and cache it.  In the TodoListController, we'll use the cache to acquire a token to the Todo List API
     string                userObjectId = notification.AuthenticationTicket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
     ClientCredential      clientCred   = new ClientCredential(ClientId, AppKey);
     AuthenticationContext authContext  = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId, notification.HttpContext.Session));
     AuthenticationResult  authResult   = await authContext.AcquireTokenByAuthorizationCodeAsync(
         notification.Code, new Uri(notification.RedirectUri), clientCred, Startup.GraphResourceId);
 }
コード例 #25
0
        private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            _log.Debug("OnAuthorizationCodeReceived: \r\n{0}\r\nCode={1}, \r\nJwtSecurityToken={2}",
                       string.Join("\r\n", notification.AuthenticationTicket.Identity.Claims.Select(f => "Claim " + f.Type + "=" + f.Value)),
                       notification.Code,
                       notification.JwtSecurityToken);

            return(Task.FromResult(0));
        }
 public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
 {
     // Acquire a Token for the Graph API and cache it.  In the TodoListController, we'll use the cache to acquire a token to the Todo List API
     string userObjectId = notification.AuthenticationTicket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
     ClientCredential clientCred = new ClientCredential(ClientId, AppKey);
     AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId, notification.HttpContext.Session));
     AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
         notification.Code, new Uri(notification.RedirectUri), clientCred, Startup.GraphResourceId);
 }
コード例 #27
0
 private Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
 {
     ClientCredential credential = new ClientCredential(ConfigHelper.ClientId, ConfigHelper.AppKey);
     string userObjectId = notification.AuthenticationTicket.Identity.FindFirst(Globals.ObjectIdClaimType).Value;
     string tenantId = notification.AuthenticationTicket.Identity.FindFirst(Globals.TenantIdClaimType).Value;
     AuthenticationContext authContext = new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, ConfigHelper.AadInstance, tenantId), new TokenDbCache(userObjectId));
     AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
         notification.Code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)), credential, ConfigHelper.GraphResourceId);
     return Task.FromResult(0);
 }
コード例 #28
0
        private static async Task <AuthenticationResult> AuthCodeReceivedCallback(AuthorizationCodeReceivedNotification context, string graphResourceId)
        {
            var code = context.Code;
            ClientCredential      credential     = new ClientCredential(clientId, appKey);
            string                signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            AuthenticationContext authContext    = new AuthenticationContext(Authority);

            return(await authContext.AcquireTokenByAuthorizationCodeAsync(
                       code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId));
        }
コード例 #29
0
 private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
 {
     string userObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
     string tenantID = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
     string authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenantID, string.Empty);
     ClientCredential cred = new ClientCredential(clientId, clientSecret);
    
     // Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
     var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, false, new NaiveSessionCache(userObjectId));
     var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(notification.Code, new Uri(redirectUri), cred, new string[] { clientId });
 }
コード例 #30
0
        /// <summary>
        /// Called when an authorization code is received.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification context)
        {
            var claimsPrincipal = new ClaimsPrincipal(context.AuthenticationTicket.Identity);

            // Upon successful sign in, get the access token & cache it using MSAL
            IConfidentialClientApplication clientApp = MSALAppBuilder.BuildConfidentialClientApplication(claimsPrincipal);

            AuthenticationResult result = await clientApp
                                          .AcquireTokenByAuthorizationCode(VeracityIntegrationOptions.DefaultScope.Split(' '), context.Code)
                                          .ExecuteAsync();
        }
コード例 #31
0
        public Task AuthCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            var oid       = Guid.Parse(notification.JwtSecurityToken.Claims.Single(c => c.Type == "oid").Value);
            var tid       = Guid.Parse(notification.JwtSecurityToken.Claims.Single(c => c.Type == "tid").Value);
            var firstname = notification.JwtSecurityToken.Claims.Single(c => c.Type == "name").Value;

            var context = new DashDocsContext();

            var customer = context.Customers.SingleOrDefault(c => c.Id == tid);

            if (customer != null)
            {
                var user = context.Users.SingleOrDefault(u => u.Id == oid && u.CustomerId == tid);
                if (user == null)
                {
                    // new user first sign-in
                    user = new User
                    {
                        Id         = oid,
                        CustomerId = tid,
                        FirstName  = firstname
                    };

                    context.Users.Add(user);
                    context.SaveChanges();
                }

                // though the application can access the claims from the returned
                // JWTToken, it's better to have custom claim properties as this eases up the usage.
                var applicationClaims = new AppClaims
                {
                    CustomerId   = tid,
                    CustomerName = customer.Name,
                    UserId       = oid,
                    DisplayName  = user.FirstName + user.LastName
                };

                var claim = new Claim("ddcs", JsonConvert.SerializeObject(applicationClaims));
                notification.AuthenticationTicket.Identity.AddClaim(claim);

                var tableStorageService = new TableStorageService();
                tableStorageService.CreateLog(tid, oid, notification.Request.RemoteIpAddress, true, null);
            }
            else
            {
                throw new UserLoggedInWithoutExistingCustomerException()
                      {
                          TenantId  = tid,
                          UserId    = oid,
                          FirstName = firstname
                      };
            }
            return(Task.FromResult(0));
        }
コード例 #32
0
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder.Create(AuthenticationConfig.ClientId)
                                                       .WithClientSecret(AuthenticationConfig.ClientSecret)
                                                       .WithRedirectUri(AuthenticationConfig.RedirectUri)
                                                       .WithAuthority(new Uri(AuthenticationConfig.Authority))
                                                       .Build();

            AuthenticationResult result = await clientApp.AcquireTokenByAuthorizationCode(new[] { "Mail.Read" }
                                                                                          , context.Code).ExecuteAsync();
        }
コード例 #33
0
        private static async Task ExchangeAuthCodeWithToken(AuthorizationCodeReceivedNotification notification, TokenProviderConfiguration configuration)
        {
            HttpContext.Current.User = new ClaimsPrincipal(notification.AuthenticationTicket.Identity);
            var c       = HttpContext.Current;
            var cache   = CacheFactoryFunc().Invoke();
            var context = configuration.ConfidentialClientApplication(cache, _debugLogger);
            var user    = await context.AcquireTokenByAuthorizationCode(new[] { configuration.Scope }, notification.Code)
                          .ExecuteAsync();

            HttpContext.Current = c;
        }
コード例 #34
0
        internal static async Task AuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            Helpers.ThrowIfConditionFailed(() => context.Code == "AAABAAAAvPM1KaPlrEqdFSBzjqfTGGBtrTYVn589oKw4lLgJ6Svz0AhPVOJr0J2-Uu_KffGlqIbYlRAyxmt-vZ7VlSVdrWvOkNhK9OaAMaSD7LDoPbBTVMEkB0MdAgBTV34l2el-s8ZI02_9PvgQaORZs7n8eGaGbcoKAoxiDn2OcKuJVplXYgrGUwU4VpRaqe6RaNzuseM7qBFbLIv4Wps8CndE6W8ccmuu6EvGC6-H4uF9EZL7gU4nEcTcvkE4Qyt8do6VhTVfM1ygRNQgmV1BCig5t_5xfhL6-xWQdy15Uzn_Df8VSsyDXe8s9cxyKlqc_AIyLFy_NEiMQFUqjZWKd_rR3A8ugug15SEEGuo1kF3jMc7dVMdE6OF9UBd-Ax5ILWT7V4clnRQb6-CXB538DlolREfE-PowXYruFBA-ARD6rwAVtuVfCSbS0Zr4ZqfNjt6x8yQdK-OkdQRZ1thiZcZlm1lyb2EquGZ8Deh2iWBoY1uNcyjzhG-L43EivxtHAp6Y8cErhbo41iacgqOycgyJWxiB5J0HHkxD0nQ2RVVuY8Ybc9sdgyfKkkK2wZ3idGaRCdZN8Q9VBhWRXPDMqHWG8t3aZRtvJ_Xd3WhjNPJC0GpepUGNNQtXiEoIECC363o1z6PZC5-E7U3l9xK06BZkcfTOnggUiSWNCrxUKS44dNqaozdYlO5E028UgAEhJ4eDtcP3PZty-0j4j5Mw0F2FmyAA",
                "context.Code is invalid.");
            notificationsFired.Add(nameof(AuthorizationCodeReceived));

            // Verify all notifications are fired.
            if (notificationsFired.Contains(nameof(RedirectToIdentityProvider)) &&
                notificationsFired.Contains(nameof(MessageReceived)) &&
                notificationsFired.Contains(nameof(SecurityTokenReceived)) &&
                notificationsFired.Contains(nameof(SecurityTokenValidated)) &&
                notificationsFired.Contains(nameof(AuthorizationCodeReceived)))
            {
                ((ClaimsIdentity)context.AuthenticationTicket.Principal.Identity).AddClaim(new Claim("ManageStore", "Allowed"));
            }

            await Task.FromResult(0);
        }
コード例 #35
0
        private static void OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context, PowerBIAuthenticationOptions options)
        {
            var code = context.Code;

            var credential = new ClientCredential(options.ClientId, options.ClientSecret);
            var tenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            var signedInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

            var authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenantId}", new TokenCache(Encoding.Default.GetBytes(signedInUserId)));
            var result = authContext.AcquireTokenByAuthorizationCode(code, options.SuccessRedirectUri, credential, options.Resource);

            TokenManager.Current.WriteToken(context.AuthenticationTicket.Identity, result.AccessToken);
        }
コード例 #36
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);
        }
コード例 #37
0
        protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
        {
            if (Options.CallbackPath.HasValue && Options.CallbackPath != (Request.PathBase + Request.Path))
            {
                return null;
            }

            OpenIdConnectMessage openIdConnectMessage = null;

            if (string.Equals(Request.Method, "POST", StringComparison.OrdinalIgnoreCase)
              && !string.IsNullOrWhiteSpace(Request.ContentType)
              && Request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase)
              && Request.Body.CanRead)
            {
                if (!Request.Body.CanSeek)
                {
                    _logger.WriteVerbose("Buffering request body");
                    MemoryStream memoryStream = new MemoryStream();
                    await Request.Body.CopyToAsync(memoryStream);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    Request.Body = memoryStream;
                }

                IFormCollection form = await Request.ReadFormAsync();
                Request.Body.Seek(0, SeekOrigin.Begin);

                openIdConnectMessage = new OpenIdConnectMessage(form);
            }

            if (openIdConnectMessage == null)
            {
                return null;
            }

            ExceptionDispatchInfo authFailedEx = null;
            string policy = string.Empty;
            try
            {
                var messageReceivedNotification = new MessageReceivedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = openIdConnectMessage
                };
                await Options.Notifications.MessageReceived(messageReceivedNotification);
                if (messageReceivedNotification.HandledResponse)
                {
                    return GetHandledResponseTicket();
                }
                if (messageReceivedNotification.Skipped)
                {
                    return null;
                }

                AuthenticationProperties properties = GetPropertiesFromState(openIdConnectMessage.State);
                if (properties == null)
                {
                    _logger.WriteWarning("The state field is missing or invalid.");
                    return null;
                }

                string nonce = null;
                if (Options.ProtocolValidator.RequireNonce)
                {
                    nonce = RetrieveNonce(openIdConnectMessage);
                }

                if (!string.IsNullOrWhiteSpace(openIdConnectMessage.Error))
                {
                    throw new OpenIdConnectProtocolException(
                        string.Format(CultureInfo.InvariantCulture,
                                      openIdConnectMessage.Error,
                                      "", openIdConnectMessage.ErrorDescription ?? string.Empty, openIdConnectMessage.ErrorUri ?? string.Empty));
                }

                if (string.IsNullOrWhiteSpace(openIdConnectMessage.IdToken))
                {
                    _logger.WriteWarning("The id_token is missing.");
                    return null;
                }

                var securityTokenReceivedNotification = new SecurityTokenReceivedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = openIdConnectMessage,
                };
                await Options.Notifications.SecurityTokenReceived(securityTokenReceivedNotification);
                if (securityTokenReceivedNotification.HandledResponse)
                {
                    return GetHandledResponseTicket();
                }
                if (securityTokenReceivedNotification.Skipped)
                {
                    return null;
                }

                // Enable Per-Policy Metadata Retreival
                if (properties.Dictionary.TryGetValue(PolicyParameter, out policy))
                {
                    B2CConfigurationManager mgr = Options.ConfigurationManager as B2CConfigurationManager;
                    _configuration = await mgr.GetConfigurationAsync(Context.Request.CallCancelled, policy);
                }
                else
                {
                    _logger.WriteWarning("No policy identifier was found in the Authentication Properties of the request.");
                    return null;
                }

                TokenValidationParameters tvp = Options.TokenValidationParameters.Clone();
                IEnumerable<string> issuers = new[] { _configuration.Issuer };
                tvp.ValidIssuers = (tvp.ValidIssuers == null ? issuers : tvp.ValidIssuers.Concat(issuers));
                tvp.IssuerSigningTokens = (tvp.IssuerSigningTokens == null ? _configuration.SigningTokens : tvp.IssuerSigningTokens.Concat(_configuration.SigningTokens));

                SecurityToken validatedToken;
                ClaimsPrincipal principal = Options.SecurityTokenHandlers.ValidateToken(openIdConnectMessage.IdToken, tvp, out validatedToken);
                ClaimsIdentity claimsIdentity = principal.Identity as ClaimsIdentity;

                JwtSecurityToken jwt = validatedToken as JwtSecurityToken;
                AuthenticationTicket ticket = new AuthenticationTicket(claimsIdentity, properties);

                if (!string.IsNullOrWhiteSpace(openIdConnectMessage.SessionState))
                {
                    ticket.Properties.Dictionary[OpenIdConnectSessionProperties.SessionState] = openIdConnectMessage.SessionState;
                }

                if (!string.IsNullOrWhiteSpace(_configuration.CheckSessionIframe))
                {
                    ticket.Properties.Dictionary[OpenIdConnectSessionProperties.CheckSessionIFrame] = _configuration.CheckSessionIframe;
                }

                if (Options.UseTokenLifetime)
                {
                    DateTime issued = jwt.ValidFrom;
                    if (issued != DateTime.MinValue)
                    {
                        ticket.Properties.IssuedUtc = issued.ToUniversalTime();
                    }
                    DateTime expires = jwt.ValidTo;
                    if (expires != DateTime.MinValue)
                    {
                        ticket.Properties.ExpiresUtc = expires.ToUniversalTime();
                    }
                    ticket.Properties.AllowRefresh = false;
                }

                var securityTokenValidatedNotification = new SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    AuthenticationTicket = ticket,
                    ProtocolMessage = openIdConnectMessage,
                };
                await Options.Notifications.SecurityTokenValidated(securityTokenValidatedNotification);
                if (securityTokenValidatedNotification.HandledResponse)
                {
                    return GetHandledResponseTicket();
                }
                if (securityTokenValidatedNotification.Skipped)
                {
                    return null;
                }
                ticket = securityTokenValidatedNotification.AuthenticationTicket;

                var protocolValidationContext = new OpenIdConnectProtocolValidationContext
                {
                    AuthorizationCode = openIdConnectMessage.Code,
                    Nonce = nonce,
                };

                Options.ProtocolValidator.Validate(jwt, protocolValidationContext);
                if (openIdConnectMessage.Code != null)
                {
                    var authorizationCodeReceivedNotification = new AuthorizationCodeReceivedNotification(Context, Options)
                    {
                        AuthenticationTicket = ticket,
                        Code = openIdConnectMessage.Code,
                        JwtSecurityToken = jwt,
                        ProtocolMessage = openIdConnectMessage,
                        RedirectUri = ticket.Properties.Dictionary.ContainsKey(OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey) ?
                            ticket.Properties.Dictionary[OpenIdConnectAuthenticationDefaults.RedirectUriUsedForCodeKey] : string.Empty,
                    };
                    await Options.Notifications.AuthorizationCodeReceived(authorizationCodeReceivedNotification);
                    if (authorizationCodeReceivedNotification.HandledResponse)
                    {
                        return GetHandledResponseTicket();
                    }
                    if (authorizationCodeReceivedNotification.Skipped)
                    {
                        return null;
                    }
                    ticket = authorizationCodeReceivedNotification.AuthenticationTicket;
                }

                return ticket;
            }
            catch (Exception exception)
            {
                authFailedEx = ExceptionDispatchInfo.Capture(exception);
            }

            if (authFailedEx != null)
            {
                _logger.WriteError("Exception occurred while processing message: '" + authFailedEx.ToString());

                if (Options.RefreshOnIssuerKeyNotFound && authFailedEx.SourceException.GetType().Equals(typeof(SecurityTokenSignatureKeyNotFoundException)))
                {
                    B2CConfigurationManager mgr = Options.ConfigurationManager as B2CConfigurationManager;
                    mgr.RequestRefresh(policy);
                }

                var authenticationFailedNotification = new AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions>(Context, Options)
                {
                    ProtocolMessage = openIdConnectMessage,
                    Exception = authFailedEx.SourceException
                };
                await Options.Notifications.AuthenticationFailed(authenticationFailedNotification);
                if (authenticationFailedNotification.HandledResponse)
                {
                    return GetHandledResponseTicket();
                }
                if (authenticationFailedNotification.Skipped)
                {
                    return null;
                }

                authFailedEx.Throw();
            }

            return null;
        }
コード例 #38
-1
        /*
         * Callback function when an authorization code is received
         */
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            // Extract the code from the response notification
            var code = notification.Code;

            string     signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            TokenCache userTokenCache = new MSALSessionCache(signedInUserID, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
        }