public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            // Use MSAL to swap the code for an access token
            // Extract the code from the response notification
            var code = context.ProtocolMessage.Code;

            string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;

            // TODO: Cache tokens?
            var tokenCache = new TokenCache();

            var redirectUri = new UriBuilder(context.Request.Scheme, context.Request.Host.Host, context.Request.Host.Port ?? 80, context.Request.PathBase + "/signin-oidc");
            var cca         = new ConfidentialClientApplication(_azureAdB2COptions.ClientId, _azureAdB2COptions.Authority, redirectUri.Uri.ToString(), new ClientCredential(_azureAdB2COptions.ClientSecret), tokenCache, null);

            var result = await cca.AcquireTokenByAuthorizationCodeAsync(code, _azureAdB2COptions.ScopeString.Split(' '));

            context.HandleCodeRedemption(result.AccessToken, result.IdToken);

            // Check if we have an attendee record for this user, and load it up if we do.
            var attendee = await _apiClient.GetMeAsync(result.AccessToken);

            // If we do, load additional claims. If not, don't and the filter will take care of "welcoming" the user :)
            if (attendee != null)
            {
                var claimsIdentity = (ClaimsIdentity)context.Principal.Identity;
                AttendeeClaimMapper.UpdateClaims(claimsIdentity, attendee);
            }
        }
Example #2
0
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            string authority    = context.Options.Authority;
            string clientId     = context.Options.ClientId;
            string clientSecret = context.Options.ClientSecret;
            string redirectUri  = context.TokenEndpointRequest.RedirectUri;
            string key          = context.Principal.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier");
            string code         = context.TokenEndpointRequest.Code;
            //IEnumerable<string> scopes = _azOptions.Scopes.Split(";").Where(c => !string.IsNullOrEmpty(c));
            IEnumerable <string> scopes = new string[] { "api://core/.default" };
            IDistributedCache    cache  = context.HttpContext.RequestServices.GetService <IDistributedCache>();

            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
                                                 .Create(clientId)
                                                 .WithClientSecret(clientSecret)
                                                 .WithAuthority(authority)
                                                 .WithRedirectUri(redirectUri)
                                                 .Build();


            TokenCacheHelper.Initialize(key: key,
                                        distributedCache: cache,
                                        tokenCache: app.UserTokenCache);

            var result = await app.AcquireTokenByAuthorizationCode(scopes, code)
                         .ExecuteAsync();

            context.HandleCodeRedemption(result.AccessToken, result.IdToken);
        }
            public Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
            {
                // Use MSAL to swap the code for an access token
                // Extract the code from the response notification
                var code = context.ProtocolMessage.Code;

                string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;

                // return Task.FromResult(0);
                return(Task.CompletedTask);

                // TokenCache userTokenCache = new MSALSessionCache(signedInUserID, context.HttpContext).GetMsalCacheInstance();
                // ConfidentialClientApplication cca = new ConfidentialClientApplication(AzureAdB2COptions.ClientId, AzureAdB2COptions.Authority, AzureAdB2COptions.RedirectUri, new ClientCredential(AzureAdB2COptions.ClientSecret), userTokenCache, null);
                // try
                // {
                //     AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, AzureAdB2COptions.ApiScopes.Split(' '));

                //     context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                // }
                // catch
                // {
                //     //TODO: Handle
                //     throw;
                // }
            }
Example #4
0
        /// <summary>
        /// Redeems the authorization code by calling AcquireTokenByAuthorizationCodeAsync in order to ensure
        /// that the cache has a token for the signed-in user, which will then enable the controllers (like the
        /// TodoController, to call AcquireTokenSilentAsync successfully.
        /// </summary>
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedContext context)
        {
            // Acquire a Token for the Graph API and cache it using ADAL. In the TodoListController, we'll use the cache to acquire a token for the Todo List API
            string     userObjectId   = (context.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
            string     signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            var        code           = context.ProtocolMessage.Code;
            TokenCache userTokenCache = new MSALSessionCache(signedInUserID, context.HttpContext).GetMsalCacheInstance();

            ConfidentialClientApplication cca = new ConfidentialClientApplication(azureAdOptions.ClientId, azureAdOptions.Authority, azureAdOptions.RedirectUri, new ClientCredential(azureAdOptions.ClientSecret), userTokenCache, null);

            try
            {
                var scopes = azureAdOptions.ApiScopes.Split(' ');
                var result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);

                //AcquireTokenSilentAsync(scopes, cca.Users.FirstOrDefault(), azureAdOptions.Authority, false);


                context.HandleCodeRedemption(result.AccessToken, result.IdToken);
            }
            catch (Exception ex)
            {
                //TODO: Handle
                throw;
            }
            // Notify the OIDC middleware that we already took care of code redemption.
        }
Example #5
0
        /// <summary>
        /// In a Web App, adds, to the MSAL.NET cache, the account of the user authenticating to the Web App, when the authorization code is received (after the user
        /// signed-in and consented)
        /// An On-behalf-of token contained in the <see cref="AuthorizationCodeReceivedContext"/> is added to the cache, so that it can then be used to acquire another token on-behalf-of the
        /// same user in order to call to downstream APIs.
        /// </summary>
        /// <param name="context">The context used when an 'AuthorizationCode' is received over the OpenIdConnect protocol.</param>
        /// <example>
        /// From the configuration of the Authentication of the ASP.NET Core Web API:
        /// <code>OpenIdConnectOptions options;</code>
        ///
        /// Subscribe to the authorization code recieved event:
        /// <code>
        ///  options.Events = new OpenIdConnectEvents();
        ///  options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;
        /// }
        /// </code>
        ///
        /// And then in the OnAuthorizationCodeRecieved method, call <see cref="AddAccountToCacheFromAuthorizationCode"/>:
        /// <code>
        /// private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        /// {
        ///   var tokenAcquisition = context.HttpContext.RequestServices.GetRequiredService<ITokenAcquisition>();
        ///    await _tokenAcquisition.AddAccountToCacheFromAuthorizationCode(context, new string[] { "user.read" });
        /// }
        /// </code>
        /// </example>
        public async Task AddAccountToCacheFromAuthorizationCode(AuthorizationCodeReceivedContext context, IEnumerable <string> scopes)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (scopes == null)
            {
                throw new ArgumentNullException(nameof(scopes));
            }

            try
            {
                // As AcquireTokenByAuthorizationCodeAsync is asynchronous we want to tell ASP.NET core that we are handing the code
                // even if it's not done yet, so that it does not concurrently call the Token endpoint.
                context.HandleCodeRedemption();

                var application = BuildConfidentialClientApplication(context.HttpContext, context.Principal);

                // Do not share the access token with ASP.NET Core otherwise ASP.NET will cache it and will not send the OAuth 2.0 request in
                // case a further call to AcquireTokenByAuthorizationCodeAsync in the future for incremental consent (getting a code requesting more scopes)
                // Share the ID Token
                var result = await application.AcquireTokenByAuthorizationCode(scopes.Except(scopesRequestedByMsalNet), context.ProtocolMessage.Code)
                             .ExecuteAsync();

                context.HandleCodeRedemption(null, result.IdToken);
            }
            catch (MsalException ex)
            {
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Example #6
0
        public override async Task AuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            var principal = context.Principal;

            var request    = context.HttpContext.Request;
            var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
            var properties = context.Properties;

            var surveysTokenService = context.HttpContext.RequestServices.GetService <ISurveysTokenService>();

            try
            {
                var result = await surveysTokenService.RequestTokenAsync(
                    principal,
                    context.ProtocolMessage.Code,
                    currentUri,
                    _adOptions.WebApiResourceId)
                             .ConfigureAwait(false);

                context.HandleCodeRedemption(result.AccessToken, result.IdToken);
            }
            catch
            {
                // If an exception is thrown within this event, the user is never set on the OWIN middleware,
                // so there is no need to sign out.  However, the access token could have been put into the
                // cache so we need to clean it up.
                await surveysTokenService.ClearCacheAsync(principal)
                .ConfigureAwait(false);

                throw;
            }
        }
Example #7
0
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            //var clientCredential = new ClientCredential(context.Options.ClientSecret);
            var confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                .Create(context.Options.ClientId)
                                                .WithClientSecret(context.Options.ClientSecret)
                                                .WithAuthority(context.Options.Authority)
                                                .WithRedirectUri(_options.RedirectUri)
                                                .Build();

            //var userId = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            //var tokenCache = new SessionTokenCache(context.HttpContext, userId);

            //var confidentialClientApplication = new ConfidentialClientApplication(
            //    context.Options.ClientId,
            //    context.Options.Authority,
            //    _options.RedirectUri,
            //    clientCredential,
            //    tokenCache.GetInstance(),
            //    null);

            try
            {
                var authenticationResult = confidentialClientApplication.AcquireTokenByAuthorizationCode(_options.ApiScopes.Split(' '), context.ProtocolMessage.Code);
                //context.HandleCodeRedemption(authenticationResult.AccessToken, authenticationResult.IdToken);
            }
            catch (Exception ex)
            {
                // TODO: Handle
                throw;
            }
        }
Example #8
0
        public override Task AuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            context.TokenEndpointRequest.ClientAssertionType = OidcConstants.ClientAssertionTypes.JwtBearer;
            context.TokenEndpointRequest.ClientAssertion     = _assertionService.CreateClientToken();

            return(Task.CompletedTask);
        }
Example #9
0
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedContext context)
        {
            _logger.LogDebug(string.Format(CultureInfo.InvariantCulture, LogMessages.MethodBegin, nameof(OnAuthorizationCodeReceivedAsync)));
            await s_onAuthorizationCodeReceived(context).ConfigureAwait(false);

            _logger.LogDebug(string.Format(CultureInfo.InvariantCulture, LogMessages.MethodEnd, nameof(OnAuthorizationCodeReceivedAsync)));
        }
            public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
            {
                // Use MSAL to swap the code for an access token
                // Extract the code from the response notification
                var code = context.ProtocolMessage.Code;

                string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
                IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(AzureAdB2COptions.ClientId)
                                                     .WithB2CAuthority(AzureAdB2COptions.Authority)
                                                     .WithRedirectUri(AzureAdB2COptions.RedirectUri)
                                                     .WithClientSecret(AzureAdB2COptions.ClientSecret)
                                                     .Build();

                new MSALStaticCache(signedInUserID, context.HttpContext).EnablePersistence(cca.UserTokenCache);

                try
                {
                    AuthenticationResult result = await cca.AcquireTokenByAuthorizationCode(AzureAdB2COptions.ApiScopes.Split(' '), code)
                                                  .ExecuteAsync();


                    context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                }
                catch (Exception ex)
                {
                    //TODO: Handle
                    throw ex;
                }
            }
Example #11
0
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedContext context)
        {
            var userId    = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            var referers  = context.HttpContext.Request.Headers["Referer"].ToString().Split('/').FirstOrDefault(t => t.ToLower().StartsWith("b2c_1")).ToLower();
            var authority = context.Options.Authority.Replace("b2c_1_susi", referers);

            var confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                .Create(context.Options.ClientId)
                                                .WithClientSecret(context.Options.ClientSecret)
                                                .WithAuthority(authority)
                                                .WithRedirectUri(_options.RedirectUri)
                                                .Build();

            try
            {
                var authenticationResult = await confidentialClientApplication
                                           .AcquireTokenByAuthorizationCode(_options.ApiScopes.Split(' '), context.ProtocolMessage.Code)
                                           .WithB2CAuthority(authority)
                                           .ExecuteAsync();

                context.HandleCodeRedemption(authenticationResult.AccessToken, authenticationResult.IdToken);
            }
            catch (Exception ex)
            {
                // TODO: Handle
                //throw ex;
            }
        }
Example #12
0
        protected virtual async Task RedeemAuthorizationCodeAsync(AuthorizationCodeReceivedContext context)
        {
            var configuration = await context.Options.ConfigurationManager.GetConfigurationAsync(CancellationToken.None);

            var    requestMessage = new HttpRequestMessage(HttpMethod.Post, configuration.TokenEndpoint);
            string authInfo       = context.TokenEndpointRequest.ClientId + ":" + context.TokenEndpointRequest.ClientSecret;

            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", authInfo);
            var msg = context.TokenEndpointRequest.Clone();

            msg.ClientSecret       = null;
            requestMessage.Content = new FormUrlEncodedContent(msg.Parameters);


            var responseMessage = await context.Backchannel.SendAsync(requestMessage);

            if (!responseMessage.IsSuccessStatusCode)
            {
                Console.WriteLine(await responseMessage.Content.ReadAsStringAsync());
                return;
            }

            try
            {
                var responseContent = await responseMessage.Content.ReadAsStringAsync();

                var message = new OpenIdConnectMessage(responseContent);
                context.HandleCodeRedemption(message);
            }
            catch (Exception)
            {
            }
        }
        static async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            Debug.WriteLine($"4. Begin {nameof(OnAuthorizationCodeReceived)}");
            await onAuthorizationCodeReceived(context);

            Debug.WriteLine($"4. End - {nameof(OnAuthorizationCodeReceived)}");
        }
        /// <summary>
        /// Is called whenever B2C retrieves a new auth token.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            // Use MSAL to swap the code for an access token
            // Extract the authorization code from the response notification
            var code              = context.ProtocolMessage.Code;
            var signedInUserId    = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userTokenCache    = new MsalSessionCache(signedInUserId, context.HttpContext).GetMsalCacheInstance();
            var clientApplication = new ConfidentialClientApplication(
                AzureAdB2COptions.ClientId,
                AzureAdB2COptions.Authority,
                AzureAdB2COptions.RedirectUri,
                new ClientCredential(AzureAdB2COptions.ClientSecret),
                userTokenCache,
                null);

            // try to retrieve the baerer token
            try
            {
                var result = await clientApplication.AcquireTokenByAuthorizationCodeAsync(code, AzureAdB2COptions.ApiScopes.Split(' '));

                context.HandleCodeRedemption(result.AccessToken, result.IdToken);
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message);
                throw;
            }
        }
Example #15
0
            public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
            {
                // Use MSAL to swap the code for an access token
                // Extract the code from the response notification
                var authorization_code = context.ProtocolMessage.Code;

                string signedInUserID = context.Principal.FindFirst(c => c.Type == "userId").Value;

                //string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
                IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(AzureAdB2COptions.ClientId)
                                                     .WithB2CAuthority(AzureAdB2COptions.Authority)
                                                     .WithRedirectUri(AzureAdB2COptions.RedirectUri)
                                                     .WithClientSecret(AzureAdB2COptions.ClientSecret)
                                                     .Build();

                try
                {
                    AuthenticationResult result = await cca.AcquireTokenByAuthorizationCode(AzureAdB2COptions.DataApiScope.Split(' '), authorization_code)
                                                  .ExecuteAsync();

                    context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                    Startup.userTokenCache[signedInUserID] = result.AccessToken;
                    Debug.WriteLine(result.AccessToken + "\n\n\n\n", "\n\n\n\nAccess Token\n\t");
                }
                catch (Exception ex)
                {
                    //TODO:
                    Debug.WriteLine(ex.ToString() + "\n\n\n\n", "\n\n\n\nFetch access token failed\n\t");
                    throw;
                }
            }
Example #16
0
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedContext context)
        {
            _logger.LogDebug($"4. Begin {nameof(OnAuthorizationCodeReceivedAsync)}");
            await s_onAuthorizationCodeReceived(context).ConfigureAwait(false);

            _logger.LogDebug($"4. End - {nameof(OnAuthorizationCodeReceivedAsync)}");
        }
            public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
            {
                // Use MSAL to swap the code for an access token
                // Extract the code from the response notification
                var code = context.ProtocolMessage.Code;

                string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
                string displayName    = context.Principal.FindFirst("Name").Value;
                string email          = context.Principal.FindFirst("Emails").Value;
                string country        = String.Empty;

                if (context.Principal.FindFirst("Country") != null)
                {
                    country = context.Principal.FindFirst("Country").Value;
                }

                TokenCache userTokenCache         = new MSALSessionCache(signedInUserID, context.HttpContext).GetMsalCacheInstance();
                ConfidentialClientApplication cca = new ConfidentialClientApplication(AzureAdB2COptions.ClientId, AzureAdB2COptions.Authority, AzureAdB2COptions.RedirectUri, new ClientCredential(AzureAdB2COptions.ClientSecret), userTokenCache, null);

                try
                {
                    AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, AzureAdB2COptions.ApiScopes.Split(' '));


                    context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                }
                catch (Exception ex)
                {
                    //TODO: Handle
                    throw;
                }
            }
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            var clientCredential = new ClientCredential(context.Options.ClientSecret);
            var userId           = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            var tokenCache       = new SessionTokenCache(context.HttpContext, userId);

            var confidentialClientApplication = new ConfidentialClientApplication(
                context.Options.ClientId,
                context.Options.Authority,
                _options.RedirectUri,
                clientCredential,
                tokenCache.GetInstance(),
                null);

            try
            {
                var authenticationResult = await confidentialClientApplication.AcquireTokenByAuthorizationCodeAsync(context.ProtocolMessage.Code, _options.ApiScopes.Split(' '));

                context.HandleCodeRedemption(authenticationResult.AccessToken, authenticationResult.IdToken);
            }
            catch (Exception ex)
            {
                // TODO: Handle
                throw;
            }
        }
        public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            // Use MSAL to swap the code for an access token
            // Extract the code from the response notification
            var code = context.ProtocolMessage.Code;

            foreach (var claim in context.Ticket.Principal.Claims)
            {
                System.Console.WriteLine(claim.Type + "-->" + claim.Value);
            }

            string     signedInUserID         = context.Ticket.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            TokenCache userTokenCache         = new MSALSessionCache(signedInUserID, context.HttpContext).GetMsalCacheInstance();
            ConfidentialClientApplication cca = new ConfidentialClientApplication(AzureAdB2COptions.ClientId, AzureAdB2COptions.Authority, AzureAdB2COptions.RedirectUri, new ClientCredential(AzureAdB2COptions.ClientSecret), userTokenCache, null);

            try
            {
                AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, AzureAdB2COptions.ApiScopes.Split(' '));


                context.HandleCodeRedemption(result.AccessToken, result.IdToken);
            }
            catch (Exception ex)
            {
                //TODO: Handle
                throw;
            }
        }
Example #20
0
        private static async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedContext context)
        {
            Debug.WriteLine($"4. Begin {nameof(OnAuthorizationCodeReceivedAsync)}");
            await s_onAuthorizationCodeReceived(context).ConfigureAwait(false);

            Debug.WriteLine($"4. End - {nameof(OnAuthorizationCodeReceivedAsync)}");
        }
Example #21
0
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            // Acquire a Token for the Graph API and cache it using ADAL.
            string           userObjectId = (context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
            ClientCredential clientCred   = new ClientCredential(ClientId, ClientSecret);

            // Gets Authentication Tokens From Azure
            AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId, context.HttpContext.Session));

            // Gets the Access Token To Graph API
            AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
                context.ProtocolMessage.Code, new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]), clientCred, GraphResourceId);

            // Gets the Access Token for Application Only Permissions
            AuthenticationResult clientAuthResult = await authContext.AcquireTokenAsync(GraphResourceId, clientCred);

            // The user's unique identifier from the signin event
            string userId = authResult.UserInfo.UniqueId;

            // Get the users roles and groups from the Graph Api. Then return the roles and groups in a new identity
            ClaimsIdentity identity = await GetUsersRoles(clientAuthResult.AccessToken, userId);

            // Add the roles to the Principal User
            context.Ticket.Principal.AddIdentity(identity);

            // Notify the OIDC middleware that we already took care of code redemption.
            context.HandleCodeRedemption();
        }
Example #22
0
        public override async Task AuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            var principal           = context.AuthenticationTicket.Principal;
            var surveysTokenService = context.HttpContext.RequestServices.GetService <ISurveysTokenService>();

            try
            {
                await surveysTokenService.RequestTokenAsync(
                    principal,
                    context.ProtocolMessage.Code,
                    context.AuthenticationTicket.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey],
                    _adOptions.WebApiResourceId)
                .ConfigureAwait(false);
            }
            catch
            {
                // If an exception is thrown within this event, the user is never set on the OWIN middleware,
                // so there is no need to sign out.  However, the access token could have been put into the
                // cache so we need to clean it up.
                await surveysTokenService.ClearCacheAsync(principal)
                .ConfigureAwait(false);

                throw;
            }
        }
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            var confidentialClientApplication = ConfidentialClientApplicationBuilder.Create(context.Options.ClientId)
                                                .WithClientSecret(context.Options.ClientSecret)
                                                .WithB2CAuthority(context.Options.Authority)
                                                .WithRedirectUri(_options.RedirectUri)
                                                .Build();

            var userId     = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            var tokenCache = new SessionTokenCache(context.HttpContext, userId);

            tokenCache.Initialize(confidentialClientApplication.UserTokenCache);

            try
            {
                var authenticationResult = await confidentialClientApplication.AcquireTokenByAuthorizationCode(_options.ApiScopes.Split(' '), context.ProtocolMessage.Code)
                                           .ExecuteAsync();

                context.HandleCodeRedemption(authenticationResult.AccessToken, authenticationResult.IdToken);
            }
            catch (Exception ex)
            {
                // TODO: Handle
                throw;
            }
        }
    public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
    {
        var clientCredential = new ClientCredential(context.Options.ClientSecret);
        var userId           = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
        var userTokenCache   = new MSALSessionCache(userId, context.HttpContext).GetMsalCacheInstance();
        var confidentialClientApplication = new ConfidentialClientApplication(
            context.Options.ClientId,
            context.Options.Authority,
            $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}",
            clientCredential,
            userTokenCache,
            null);

        try
        {
            var authenticationResult = await confidentialClientApplication.AcquireTokenByAuthorizationCodeAsync(
                context.ProtocolMessage.Code,
                new[]
            {
                "https://contoso.onmicrosoft.com/api/user_impersonation"
            });

            context.HandleCodeRedemption(authenticationResult.AccessToken, authenticationResult.IdToken);
        }
        catch (Exception ex)
        {
            // TODO: Handle.
            throw;
        }
    }
Example #25
0
            public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
            {
                // Use MSAL to swap the code for an access token
                // Extract the code from the response notification
                var code = context.ProtocolMessage.Code;

                string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
                IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(AzureAdB2COptions.ClientId)
                                                     .WithB2CAuthority(AzureAdB2COptions.Authority)
                                                     .WithRedirectUri(AzureAdB2COptions.RedirectUri)
                                                     .WithClientSecret(AzureAdB2COptions.ClientSecret)
                                                     .Build();

                new MSALStaticCache(signedInUserID, context.HttpContext).EnablePersistence(cca.UserTokenCache);

                if (context.Principal != null)
                {
                    using (var scope = _scopeFactory.CreateScope())
                    {
                        var db = scope.ServiceProvider.GetRequiredService <DataContext>();

                        string email = context.Principal.Identities.First().Claims.Where(x => x.Type == "emails").First().Value;

                        var user = db.Users.Where(x => x.Email == email).FirstOrDefault();

                        if (user == null)
                        {
                            string firstName = context.Principal.Identities.First().Claims.Where(x => x.Type == ClaimTypes.GivenName).First().Value;

                            db.Users.Add(new User()
                            {
                                Email = email, Role = Enums.Role.User, Name = firstName
                            });
                            db.SaveChanges();

                            user = db.Users.Include(x => x.Role).Where(x => x.Email == email).FirstOrDefault();
                        }

                        context.Principal.Identities.First().AddClaim(new Claim(ClaimTypes.Role, user.Role.ToString()));
                        context.Principal.Identities.First().AddClaim(new Claim(context.Principal.Identities.First().NameClaimType, user.Name));
                        context.Principal.Identities.First().AddClaim(new Claim(ClaimTypes.Email, user.Email.ToString()));
                    }

                    var p = context.Principal.Identities.First();
                }

                try
                {
                    AuthenticationResult result = await cca.AcquireTokenByAuthorizationCode(AzureAdB2COptions.ApiScopes.Split(' '), code)
                                                  .ExecuteAsync();

                    context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                }
                catch
                {
                    //TODO: Handle
                    throw;
                }
            }
Example #26
0
 private void HandleServerException(AuthorizationCodeReceivedContext arg, ServerException e)
 {
     _logger?.Error(e);
     if (e.Status == HttpStatusCode.NotAcceptable)
     {
         arg.Response.Redirect(e.GetErrorData <ValidationError>().Url); //Getting the redirect url from the error message.
     }
 }
Example #27
0
        //private Task HandleTicketRecieved(TicketReceivedContext context)
        //{
        //    _log.LogWarning($"ticket received");

        //    return Task.CompletedTask;
        //}

        //private Task HandleTokenResponseRecieved(TokenResponseReceivedContext context)
        //{
        //    _log.LogWarning($"token response received");


        //    return Task.CompletedTask;
        //}

        //private Task HandleUserInformationResponseRecieved(UserInformationReceivedContext context)
        //{
        //    _log.LogWarning($"user info received");


        //    return Task.CompletedTask;
        //}

        private async Task HandleAuthorizationCodeRecieved(AuthorizationCodeReceivedContext context)
        {
            _log.LogWarning($"authorization code received {context.JwtSecurityToken}");

            if (!string.IsNullOrWhiteSpace(context.JwtSecurityToken.RawPayload))
            {
                await _oidcHybridFlowHelper.CaptureJwt(context.Principal, context.JwtSecurityToken.RawPayload);
            }
        }
Example #28
0
        private static Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            var passcode        = $"{context.Options.ClientId}:{context.Options.ClientSecret}";
            var plainTextBytes  = System.Text.Encoding.UTF8.GetBytes(passcode);
            var authHeaderValue = Convert.ToBase64String(plainTextBytes);

            context.Backchannel.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);
            return(Task.CompletedTask);
        }
Example #29
0
 private async Task AcquireTokenForMicrosoftGraph(AuthorizationCodeReceivedContext context)
 {
     // Acquire a Token for the Graph API and cache it in Session.
     string                userObjectId = context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
     ClientCredential      clientCred   = new ClientCredential(ClientId, ClientSecret);
     AuthenticationContext authContext  = new AuthenticationContext(Authority, new SessionCache(userObjectId, context.HttpContext));
     AuthenticationResult  authResult   = await authContext.AcquireTokenByAuthorizationCodeAsync(
         context.JwtSecurityToken.Id, new Uri(context.ProtocolMessage.RedirectUri), clientCred, GraphResourceId);
 }
        // Redeem the auth code for a token to the Graph API and cache it for later.
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        {
            // Redeem auth code for access token and cache it for later use
            context.HttpContext.User = context.Ticket.Principal;
            IAzureAdTokenService tokenService = (IAzureAdTokenService)context.HttpContext.RequestServices.GetService(typeof(IAzureAdTokenService));
            await tokenService.RedeemAuthCodeForAadGraph(context.ProtocolMessage.Code, context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]);

            // Notify the OIDC middleware that we already took care of code redemption.
            context.HandleCodeRedemption();
        }