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();
        }
Пример #2
0
        public async Task <string> GetTokenUsingAuthorizationCode(string code)
        {
            string[] scopes = { "User.Read" };
            var      result = await client.AcquireTokenByAuthorizationCode(scopes, code).ExecuteAsync().ConfigureAwait(false);

            return(result.AccessToken);
        }
Пример #3
0
        private async Task <GraphServiceClient> GetGraphService(string codeAuthencation)
        {
            string clientId    = _config.GetSection(AppSettingKey.ClientId).Value;
            string secret      = _config.GetSection(AppSettingKey.SecretKey).Value;
            string tanent      = _config.GetSection(AppSettingKey.TanentId).Value;
            string authenUrl   = _config.GetSection(AppSettingKey.AuthenUrl).Value;
            string redirectUrl = _config.GetSection(AppSettingKey.RedirectUrl).Value;
            string authority   = String.Format("{0}{1}", authenUrl, tanent);

            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
                                                 .Create(clientId)
                                                 .WithRedirectUri(redirectUrl)
                                                 .WithClientSecret(secret)
                                                 .WithAuthority(authority)
                                                 .Build();
            AuthorizationCodeProvider auth = new AuthorizationCodeProvider(app, scopes);
            var authenResult = await app.AcquireTokenByAuthorizationCode(scopes, codeAuthencation).ExecuteAsync();

            GraphServiceClient service = new GraphServiceClient(new DelegateAuthenticationProvider(
                                                                    async(request) =>
            {
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authenResult.AccessToken);
                await Task.Yield();
            }
                                                                    ));

            return(service);
        }
            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;
                }
            }
Пример #5
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);
        }
        /// <summary>
        /// Obtains a token from the Azure Active Directory service, using the specified authorization code authenticate.
        /// </summary>
        /// <param name="requestContext">The details of the authentication request.</param>
        /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param>
        /// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls.</returns>
        public override async ValueTask <AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken = default)
        {
            using DiagnosticScope scope = _clientDiagnostics.CreateScope("Azure.Identity.AuthorizationCodeCredential.GetToken");

            scope.Start();

            try
            {
                AccessToken token = default;

                if (_account is null)
                {
                    AuthenticationResult result = await _confidentialClient.AcquireTokenByAuthorizationCode(requestContext.Scopes, _authCode).ExecuteAsync().ConfigureAwait(false);

                    _account = result.Account;

                    token = new AccessToken(result.AccessToken, result.ExpiresOn);
                }
                else
                {
                    AuthenticationResult result = await _confidentialClient.AcquireTokenSilent(requestContext.Scopes, _account).ExecuteAsync().ConfigureAwait(false);

                    token = new AccessToken(result.AccessToken, result.ExpiresOn);
                }

                return(token);
            }
            catch (Exception e)
            {
                scope.Failed(e);

                throw;
            }
        }
Пример #7
0
        /*
         * 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;
            }
        }
Пример #8
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;
                }
            }
Пример #9
0
        public string GetAccessToken(string authorizationCode, string clientID, string clientSecret, string redirectUri)
        {
            //Redirect uri must match the redirect_uri used when requesting Authorization code.
            //Note: If you use a redirect back to Default, as in this sample, you need to add a forward slash
            //such as http://localhost:13526/

            string authorityUri = Properties.Settings.Default.AADAuthorityUri;

            //Values are hard-coded for sample purposes
            IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder
                                                       .Create(Properties.Settings.Default.ApplicationID)
                                                       .WithRedirectUri(redirectUri)
                                                       .WithAuthority(authorityUri)
                                                       .WithClientSecret(clientSecret)
                                                       .Build();
            AuthenticationResult authResult = null;

            try
            {
                string[] scope = new string[Properties.Settings.Default.Scope.Count];
                Properties.Settings.Default.Scope.CopyTo(scope, 0);
                authResult = clientApp.AcquireTokenByAuthorizationCode(scope, authorizationCode).ExecuteAsync().Result;
            }
            catch (Exception)
            {
                throw;
            }

            return(authResult.AccessToken);
        }
Пример #10
0
        /*
         * 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}."
                });
            }
        }
Пример #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //Redirect uri must match the redirect_uri used when requesting Authorization code.
            string redirectUri  = $"{Properties.Settings.Default.RedirectUrl}Redirect";
            string authorityUri = Properties.Settings.Default.AADAuthorityUri;

            // Use Tenant Id in single tenant authentication scenario
            string tenantId  = Properties.Settings.Default.TenantId;
            Guid   emptyGuid = Guid.Empty;

            // Check whether Tenant Id is a valid guid and accordingly take action
            if (!string.IsNullOrWhiteSpace(tenantId) && Guid.TryParse(tenantId, out emptyGuid))
            {
                // Update Authority URI
                authorityUri = authorityUri.Replace("common", tenantId);
            }
            else if (!string.IsNullOrWhiteSpace(tenantId) && !Guid.TryParse(tenantId, out emptyGuid))
            {
                throw new Exception("Please enter a valid Tenant Id in configuration");
            }

            // Get the auth code
            string code = Request.Params["code"];

            if (code != null)
            {
                IConfidentialClientApplication clientApp = ConfidentialClientApplicationBuilder
                                                           .Create(Properties.Settings.Default.ApplicationID)
                                                           .WithRedirectUri(redirectUri)
                                                           .WithAuthority(authorityUri)
                                                           .WithClientSecret(Properties.Settings.Default.ApplicationSecret)
                                                           .Build();
                AuthenticationResult authResult = null;
                try
                {
                    string[] scope = new string[Properties.Settings.Default.Scope.Count];
                    Properties.Settings.Default.Scope.CopyTo(scope, 0);
                    authResult = clientApp.AcquireTokenByAuthorizationCode(scope, code).ExecuteAsync().Result;
                }
                catch (MsalException)
                {
                    throw;
                }

                //Set Session "authResult" index string to the AuthenticationResult
                Session[Utils.authResultString] = authResult;

                //Get the authentication result from the session
                Utils.authResult = (AuthenticationResult)Session[Utils.authResultString];

                Response.Redirect($"/{Utils.EmbedType}.aspx");
            }
            else
            {
                //Remove Session "authResult"
                Session[Utils.authResultString] = null;
            }
            //Redirect back to Default.aspx
            Response.Redirect("/Default.aspx");
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                // The `Authority` represents the Microsoft v2.0 authentication and authorization service.
                // The `Scope` describes the permissions that your app will need. See https://azure.microsoft.com/documentation/articles/active-directory-v2-scopes/
                ClientId              = appId,
                Authority             = "https://login.microsoftonline.com/common/v2.0",
                PostLogoutRedirectUri = redirectUri,
                RedirectUri           = redirectUri,
                Scope = "openid email profile offline_access " + graphScopes,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    // In a real application you would use IssuerValidator for additional checks,
                    // like making sure the user's organization has signed up for your app.
                    //     IssuerValidator = (issuer, token, tvp) =>
                    //     {
                    //         if (MyCustomTenantValidation(issuer))
                    //             return issuer;
                    //         else
                    //             throw new SecurityTokenInvalidIssuerException("Invalid issuer");
                    //     },
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async(context) =>
                    {
                        var code = context.Code;
                        string signedInUserID             = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        IConfidentialClientApplication cc = MsalAppBuilder.BuildConfidentialClientApplication();
                        string[] scopes = graphScopes.Split(new char[] { ' ' });

                        AuthenticationResult result = await cc.AcquireTokenByAuthorizationCode(scopes, code)
                                                      .ExecuteAsync();

                        // Check whether the login is from the MSA tenant.
                        // The sample uses this attribute to disable UI buttons for unsupported operations when the user is logged in with an MSA account.
                        var currentTenantId = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                        if (currentTenantId == "9188040d-6c67-4c5b-b112-36a304b66dad")
                        {
                            HttpContext.Current.Session.Add("AccountType", "msa");
                        }
                        // Set IsAdmin session variable to false, since the user hasn't consented to admin scopes yet.
                        HttpContext.Current.Session.Add("IsAdmin", false);
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return(Task.FromResult(0));
                    }
                }
            });
        }
Пример #13
0
        private async ValueTask <AccessToken> GetTokenImplAsync(bool async, TokenRequestContext requestContext, CancellationToken cancellationToken = default)
        {
            using CredentialDiagnosticScope scope = _pipeline.StartGetTokenScope($"{nameof(AuthorizationCodeCredential)}.{nameof(GetToken)}", requestContext);

            try
            {
                AccessToken token = default;

                if (_record is null)
                {
                    AuthenticationResult result = await _confidentialClient.AcquireTokenByAuthorizationCode(requestContext.Scopes, _authCode).ExecuteAsync(async, cancellationToken).ConfigureAwait(false);

                    _record = new AuthenticationRecord(result);

                    token = new AccessToken(result.AccessToken, result.ExpiresOn);
                }
                else
                {
                    AuthenticationResult result = await _confidentialClient.AcquireTokenSilent(requestContext.Scopes, (AuthenticationAccount)_record).ExecuteAsync(async, cancellationToken).ConfigureAwait(false);

                    token = new AccessToken(result.AccessToken, result.ExpiresOn);
                }

                return(scope.Succeeded(token));
            }
            catch (Exception e)
            {
                throw scope.FailWrapAndThrow(e);
            }
        }
Пример #14
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;
                }
            }
Пример #15
0
        public async Task <AuthenticationResult> GetAccessTokenByAuthorizationCodeAsync(ClaimsPrincipal principal, string code)
        {
            IConfidentialClientApplication app    = BuildApp(principal);
            AuthenticationResult           result = await app.AcquireTokenByAuthorizationCode(_scopes, code).ExecuteAsync().ConfigureAwait(false);

            IAccount account = await app.GetAccountAsync(principal.GetMsalAccountId());

            return(result);
        }
Пример #16
0
        public async Task <string> AddUserToTokenCache(string authorizationCode)
        {
            var result = await _msalClient
                         .AcquireTokenByAuthorizationCode(graphScopes, authorizationCode)
                         .ExecuteAsync();

            _userAccount = result.Account;

            return(result.IdToken);
        }
Пример #17
0
        public void button1_Click(object sender, EventArgs e)
        {
            string authurl = null;


            try
            {
                //Getting Authorization URL
                //Instantiating and adding properties to Confidential Client
                url = String.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", Domain.Text);
                app = ConfidentialClientApplicationBuilder.Create(ClientID.Text).WithClientSecret(Secret.Text).WithRedirectUri(redirectURI.Text).Build();
                var GeneratedURL = app.GetAuthorizationRequestUrl(scopes).WithAuthority(url, true).ExecuteAsync();
                GeneratedURL.Wait();
                authurl = GeneratedURL.Result.AbsoluteUri;
                Logger.WriteLog("Generated Authorization URL successfully: " + authurl);
            }
            catch (Microsoft.Identity.Client.MsalClientException eexc)
            {
                Logger.WriteLog("Issue encountered while generating Authorization URL: " + eexc);
                throw;
            }
            catch (System.AggregateException eexc)
            {
                Logger.WriteLog("Issue encountered while generating Authorization URL. Please check that your domain is entered correctly: " + eexc);
                throw;
            }

            //Navigating to Authorization URL
            Form2 popup = new Form2(authurl, redirectURI.Text);

            popup.ShowDialog(this);
            AuthorizationCodeform = popup.Code;
            Logger.WriteLog("Authorization Code obtained succesfully: " + AuthorizationCodeform);



            try
            {
                //Generating Access token
                url = String.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/token", Domain.Text);

                var getToken = app.AcquireTokenByAuthorizationCode(scopes, AuthorizationCodeform).WithAuthority(url, true).ExecuteAsync();
                getToken.Wait();
                accnt = getToken.Result.Account;
                string at = getToken.Result.AccessToken;
                accessToken.Text = at;
                Logger.WriteLog("Access Token obtained succesfully: " + at);
            }
            catch //Catch is generic due to possible network issues
            {
                Logger.WriteLog("Issue encountered while obtaining Authrization Code. Please check the AAD Log-in prompt error for more details. This log was generated due to empty Authorization Code");

                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;

                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)
                {
                    var             claims = context.Principal.Identities.First().Claims;
                    ApplicationUser au     = new ApplicationUser();
                    var             v      = claims.FirstOrDefault(x => ClaimTypes.Email == x.Type || x.Type == "email" || x.Type == "emails");
                    var             v1     = claims.FirstOrDefault(x => ClaimTypes.GivenName == x.Type);
                    var             v2     = claims.FirstOrDefault(x => ClaimTypes.Surname == x.Type);
                    au.Email    = v != null ? v.Value : "";
                    au.Name     = v1 != null ? v1.Value : "";
                    au.Lastname = v2 != null ? v2.Value : "";
                    var first = _context.Users.Where(x => x.Email == au.Email).Include(i => i.Role).FirstOrDefault();


                    //_context.Users.Select(x=>x).Include().FirstOrDefault(x => x.Email == au.Email);

                    if (first == null)
                    {
                        au.Role = _context.Roles.First(x => x.RoleName == Roles.User.ToString());
                        _context.Users.Add(au);
                        _context.SaveChanges();
                        first = au;
                    }
                    context.Principal.Identities.First().AddClaim(new Claim(ClaimTypes.Role, first.Role.RoleName));

                    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;
                }
            }
Пример #19
0
        public async Task <IActionResult> Auth(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "b2c/auth")] HttpRequest req,
            ILogger log)
        {
            var code  = req.Query["code"];
            var token = await confidentialClientApplication.AcquireTokenByAuthorizationCode(authorizationService.AuthorizationScopes, code).ExecuteAsync();

            var result = await apiService.CallSecureApiAsync(token.AccessToken);

            return(new OkObjectResult(result));
        }
            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())
                    {
                        _dataContext = scope.ServiceProvider.GetRequiredService <DataContext>();

                        var claims = context.Principal.Identities.First().Claims;

                        var email     = claims.FirstOrDefault(x => ClaimTypes.Email == x.Type || x.Type == "email" || x.Type == "emails")?.Value;
                        var firstName = claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
                        var lastName  = claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;

                        var user = new UserViewModel()
                        {
                            FirstName  = firstName,
                            LastName   = lastName,
                            Email      = email,
                            Role       = UserRole.User,
                            ExternalId = signedInUserID
                        };

                        _dataContext.AddUserIfNotExists(user, out var userRole);
                        context.Principal.Identities.First().AddClaim(new Claim(ClaimTypes.Role, userRole.ToString()));
                    }
                }

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

                    context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                }
                catch
                {
                    //TODO: Handle
                    throw;
                }
            }
Пример #21
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();
        }
Пример #22
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();
        }
        private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification notification)
        {
            notification.HandleCodeRedemption();

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

            AuthenticationResult result = await confidentialClient
                                          .AcquireTokenByAuthorizationCode(Globals.Scopes, notification.Code).ExecuteAsync();

            notification.HandleCodeRedemption(null, result.IdToken);
        }
        /// <summary>
        /// This handler is executed after the authorization code is received (once the user signs-in and consents) during the
        /// <a href='https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-auth-code-flow'>Authorization code flow grant flow</a> in a web app.
        /// It uses the code to request an access token from the Microsoft Identity platform and caches the tokens and an entry about the signed-in user's account in the MSAL's token cache.
        /// The access token (and refresh token) provided in the <see cref="AuthorizationCodeReceivedContext"/>, once added to the cache, are then used to acquire more tokens using the
        /// <a href='https://docs.microsoft.com/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow'>on-behalf-of flow</a> for the signed-in user's account,
        /// in order to call to downstream APIs.
        /// </summary>
        /// <param name="context">The context used when an 'AuthorizationCode' is received over the OpenIdConnect protocol.</param>
        /// <param name="scopes">scopes to request access to.</param>
        /// <example>
        /// From the configuration of the Authentication of the ASP.NET Core Web API:
        /// <code>OpenIdConnectOptions options;</code>
        ///
        /// Subscribe to the authorization code received event:
        /// <code>
        ///  options.Events = new OpenIdConnectEvents();
        ///  options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;
        /// }
        /// </code>
        ///
        /// And then in the OnAuthorizationCodeRecieved method, call <see cref="AddAccountToCacheFromAuthorizationCodeAsync"/>:
        /// <code>
        /// private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        /// {
        ///   var tokenAcquisition = context.HttpContext.RequestServices.GetRequiredService&lt;ITokenAcquisition&gt;();
        ///    await _tokenAcquisition.AddAccountToCacheFromAuthorizationCode(context, new string[] { "user.read" });
        /// }
        /// </code>
        /// </example>
        public async Task AddAccountToCacheFromAuthorizationCodeAsync(
            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. (otherwise there will be a
                // race condition ending-up in an error from Azure AD telling "code already redeemed")
                context.HandleCodeRedemption();

                // The cache will need the claims from the ID token.
                // If they are not yet in the HttpContext.User's claims, add them here.
                if (!context.HttpContext.User.Claims.Any())
                {
                    (context.HttpContext.User.Identity as ClaimsIdentity).AddClaims(context.Principal.Claims);
                }

                _application = await GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);

                // 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 is required for incremental consent (getting a code requesting more scopes)
                // Share the ID Token though
                var result = await _application
                             .AcquireTokenByAuthorizationCode(scopes.Except(_scopesRequestedByMsal), context.ProtocolMessage.Code)
                             .WithSendX5C(_microsoftIdentityOptions.SendX5C)
                             .ExecuteAsync()
                             .ConfigureAwait(false);

                context.HandleCodeRedemption(null, result.IdToken);
            }
            catch (MsalException ex)
            {
                _logger.LogInformation(
                    ex,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "Exception occurred while adding an account to the cache from the auth code. "));
                throw;
            }
        }
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            /*
             *           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(context.AuthenticationTicket.Identity));

            // Upon successful sign in, get & cache a token using MSAL
            AuthenticationResult result = await confidentialClient.AcquireTokenByAuthorizationCode(new[] { "user.readbasic.all" }, context.Code).ExecuteAsync();
        }
Пример #26
0
        public void EnsurePublicApiSurfaceExistsOnInterface()
        {
            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId)
                                                 .WithClientSecret("cats")
                                                 .Build();

            // This test is to ensure that the methods we want/need on the IConfidentialClientApplication exist and compile.  This isn't testing functionality, that's done elsewhere.
            // It's solely to ensure we know that the methods we want/need are available where we expect them since we tend to do most testing on the concrete types.

            var authCodeBuilder = app.AcquireTokenByAuthorizationCode(TestConstants.s_scope, "authorizationcode");

            PublicClientApplicationTests.CheckBuilderCommonMethods(authCodeBuilder);

            var clientBuilder = app.AcquireTokenForClient(TestConstants.s_scope)
                                .WithForceRefresh(true)
                                .WithSendX5C(true);

            PublicClientApplicationTests.CheckBuilderCommonMethods(clientBuilder);

            var onBehalfOfBuilder = app.AcquireTokenOnBehalfOf(
                TestConstants.s_scope,
                new UserAssertion("assertion", "assertiontype"))
                                    .WithSendX5C(true);

            PublicClientApplicationTests.CheckBuilderCommonMethods(onBehalfOfBuilder);

            var silentBuilder = app.AcquireTokenSilent(TestConstants.s_scope, "*****@*****.**")
                                .WithForceRefresh(false);

            PublicClientApplicationTests.CheckBuilderCommonMethods(silentBuilder);

            silentBuilder = app.AcquireTokenSilent(TestConstants.s_scope, TestConstants.s_user)
                            .WithForceRefresh(true);
            PublicClientApplicationTests.CheckBuilderCommonMethods(silentBuilder);

            var requestUrlBuilder = app.GetAuthorizationRequestUrl(TestConstants.s_scope)
                                    .WithAccount(TestConstants.s_user)
                                    .WithLoginHint("loginhint")
                                    .WithExtraScopesToConsent(TestConstants.s_scope)
                                    .WithRedirectUri(TestConstants.RedirectUri);

            PublicClientApplicationTests.CheckBuilderCommonMethods(requestUrlBuilder);

            var byRefreshTokenBuilder = ((IByRefreshToken)app).AcquireTokenByRefreshToken(TestConstants.s_scope, "refreshtoken")
                                        .WithRefreshToken("refreshtoken");

            PublicClientApplicationTests.CheckBuilderCommonMethods(byRefreshTokenBuilder);
        }
Пример #27
0
        public static async Task CodeRedemptionAsync(AuthorizationCodeReceivedContext ctx)
        {
            var id_token = ctx.ProtocolMessage.IdToken;
            var code     = ctx.ProtocolMessage.Code;
            IConfidentialClientApplication clientapp = ConfidentialClientApplicationBuilder.Create(Globals.ClientId)
                                                       .WithClientSecret(Globals.ClientSecret)
                                                       .WithRedirectUri(Globals.RedirectUri)
                                                       .WithAuthority(new Uri(Globals.Authority))
                                                       .Build();

            var authResult = await clientapp
                             .AcquireTokenByAuthorizationCode(Globals.BasicSignInScopes, code)
                             .ExecuteAsync();

            ctx.HandleCodeRedemption(authResult.AccessToken, id_token);
        }
Пример #28
0
        public static async Task OnlineMeetingModel CreateOnlineMeeting(OnlineMeetingModel request, string AuthorizationCode)
        {
            string clientId    = "a48bbd5a-13b1-4990-b00e-844e7d9d68e3";
            string clientKey   = "8iY1COU52f__QCY0~x06GH_s2~uHk9YaF6";
            string redirectUrl = "https://localhost:2000";
            string authority   = "https://login.microsoftonline.com/b0ee4cb6-0b05-4002-89c5-e29eb13f1330";

            string [] scopes = new string[] { "https://graph.micosoft.com/.default" };
            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder
                                                 .Create(clientId)
                                                 .WithRedirectUri(redirectUrl)
                                                 .WithClientSecret(clientKey)
                                                 .WithAuthority(authority)
                                                 .Build();
            AuthorizationCodeProvider auth = new AuthorizationCodeProvider(app, scopes);
            var authResult = await app.AcquireTokenByAuthorizationCode(scopes, AuthorizationCode).ExecuteAsync();
        }
Пример #29
0
        public async Task <AuthenticationResult> GetAuthenticationResultAsync(Uri redirectUri, AzureAdB2COptions options)
        {
            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create($"{options.ClientId}")
                                                 .WithRedirectUri(redirectUri.AbsoluteUri)
                                                 .WithClientSecret(options.ClientSecret)
                                                 .WithB2CAuthority(options.Authority)
                                                 .Build();

            // make sure you cannot use Refresh Token with MSAL anymore.
            var scopes = options.ApiScopes.Split(' ');

            // OAuth authorization code is contains in `code`, short live 10min.
            // https://docs.microsoft.com/ja-jp/azure/active-directory-b2c/active-directory-b2c-reference-oauth-code
            var auth = await app.AcquireTokenByAuthorizationCode(scopes, code).ExecuteAsync();

            return(auth);
        }
Пример #30
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));
            services.Configure <AzureADOptions>(options => Configuration.Bind("AzureAd", options));
            services.Configure <OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
            {
                options.Authority = options.Authority + "/v2.0/";
                options.Scope.Add("https://database.windows.net//.default"); // get token fro azure sql
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;

                options.Events.OnAuthorizationCodeReceived = async context =>
                {
                    var request       = context.HttpContext.Request;
                    string currentUri = UriHelper.BuildAbsolute(
                        request.Scheme,
                        request.Host,
                        request.PathBase,
                        options.CallbackPath);

                    var code = context.ProtocolMessage.Code;
                    string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
                    IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder
                                                         .Create(options.ClientId)
                                                         .WithClientSecret(options.ClientSecret)
                                                         .WithRedirectUri(currentUri)
                                                         .WithAuthority(options.Authority)
                                                         .Build();
                    new MSALStaticCache(signedInUserID, context.HttpContext).EnablePersistence(cca.UserTokenCache);
                    AuthenticationResult result = await cca.AcquireTokenByAuthorizationCode(options.Scope, code)
                                                  .ExecuteAsync();

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

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            });
            services.AddRazorPages();
        }