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

            SampleTokenCache tokenCache = new SampleTokenCache(userObjectId);

            var credential = new ClientCredential(ClientSecret);

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


            try
            {
                var result = await cca.AcquireTokenByAuthorizationCodeAsync(code, Scopes);
            }
            catch (MsalException ex)
            {
                context.HandleResponse();
                context.Response.Redirect($"/error/index?message={ex.Message}");
            }
        }
コード例 #3
0
        /// <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;
            }
        }
コード例 #4
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;

            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;
            }
        }
コード例 #5
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);
            }
        }
            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;
            }
        }
コード例 #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 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);
            }
        }
コード例 #9
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);
 }
コード例 #10
0
    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;
        }
    }
コード例 #11
0
        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",
                Authority             = "https://login.microsoftonline.com/{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;

                        TokenCache userTokenCache = new SessionTokenCache(signedInUserID,
                                                                          context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
                        ConfidentialClientApplication cca = new ConfidentialClientApplication(
                            appId,
                            redirectUri,
                            new ClientCredential(appSecret),
                            userTokenCache,
                            null);
                        string[] scopes = graphScopes.Split(new char[] { ' ' });

                        AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return(Task.FromResult(0));
                    }
                }
            });
        }
コード例 #12
0
        private static OpenIdConnectEvents CreateOpenIdConnectEventHandlers(B2CAuthenticationOptions authOptions, B2CPolicies policies, IDistributedCache distributedCache)
        {
            return(new OpenIdConnectEvents
            {
                OnRedirectToIdentityProvider = context => SetIssuerAddressAsync(context, policies.SignInOrSignUpPolicy),
                OnRedirectToIdentityProviderForSignOut = context => SetIssuerAddressForSignOutAsync(context, policies.SignInOrSignUpPolicy),
                OnAuthorizationCodeReceived = async context =>
                {
                    try
                    {
                        var principal = context.Principal;

                        var userTokenCache = new DistributedTokenCache(distributedCache, principal.FindFirst(Constants.ObjectIdClaimType).Value).GetMSALCache();
                        var client = new ConfidentialClientApplication(authOptions.ClientId,
                                                                       authOptions.GetAuthority(principal.FindFirst(Constants.AcrClaimType).Value),
                                                                       "https://app", // it's not really needed
                                                                       new ClientCredential(authOptions.ClientSecret),
                                                                       userTokenCache,
                                                                       null);

                        var result = await client.AcquireTokenByAuthorizationCodeAsync(context.TokenEndpointRequest.Code,
                                                                                       new[] { $"{authOptions.ApiIdentifier}/read_values" });

                        context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                    }
                    catch (Exception ex)
                    {
                        context.Fail(ex);
                    }
                },
                OnAuthenticationFailed = context =>
                {
                    context.Fail(context.Exception);
                    return Task.FromResult(0);
                },
                OnMessageReceived = context =>
                {
                    if (!string.IsNullOrEmpty(context.ProtocolMessage.Error) &&
                        !string.IsNullOrEmpty(context.ProtocolMessage.ErrorDescription))
                    {
                        if (context.ProtocolMessage.ErrorDescription.StartsWith("AADB2C90091")) // cancel profile editing
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/");
                        }
                        else if (context.ProtocolMessage.ErrorDescription.StartsWith("AADB2C90118")) // forgot password
                        {
                            context.HandleResponse();
                            context.Response.Redirect("/Account/ResetPassword");
                        }
                    }

                    return Task.FromResult(0);
                }
            });
        }
コード例 #13
0
        public async Task AuthorizationCodeRequestTestAsync()
        {
            await RunWithMockHttpAsync(
                async (httpManager, serviceBundle, receiver) =>
            {
                httpManager.AddInstanceDiscoveryMockHandler();

                var cache = new TokenCache()
                {
                    BeforeAccess = BeforeCacheAccess,
                    AfterAccess  = AfterCacheAccess
                };

                var cc  = new ClientCredential("secret");
                var app = new ConfidentialClientApplication(
                    serviceBundle,
                    MsalTestConstants.ClientId,
                    "https://" + MsalTestConstants.ProductionPrefNetworkEnvironment + "/tfp/home/policy",
                    MsalTestConstants.RedirectUri,
                    cc,
                    cache,
                    null)
                {
                    ValidateAuthority = false
                };

                httpManager.AddMockHandlerForTenantEndpointDiscovery(MsalTestConstants.AuthorityHomeTenant, "p=policy");
                httpManager.AddSuccessTokenResponseMockHandlerForPost();

                var result = await app.AcquireTokenByAuthorizationCodeAsync("some-code", MsalTestConstants.Scope)
                             .ConfigureAwait(false);
                Assert.IsNotNull(result);
                Assert.AreEqual(1, app.UserTokenCache.TokenCacheAccessor.AccessTokenCount);
                Assert.AreEqual(1, app.UserTokenCache.TokenCacheAccessor.RefreshTokenCount);

                cache = new TokenCache()
                {
                    BeforeAccess = BeforeCacheAccess,
                    AfterAccess  = AfterCacheAccess
                };

                app = new ConfidentialClientApplication(
                    MsalTestConstants.ClientId,
                    "https://" + MsalTestConstants.ProductionPrefNetworkEnvironment + "/tfp/home/policy",
                    MsalTestConstants.RedirectUri,
                    cc,
                    cache,
                    null)
                {
                    ValidateAuthority = false
                };

                IEnumerable <IAccount> users = await app.GetAccountsAsync().ConfigureAwait(false);
                Assert.AreEqual(1, users.Count());
            }).ConfigureAwait(false);
        }
コード例 #14
0
        public static async Task <String> GetAccessTokenByAuthenticationCodeAsync(string authCode, string webUrl)
        {
            ConfidentialClientApplication cca = new ConfidentialClientApplication(SettingsHelper.AppId, webUrl,
                                                                                  new ClientCredential(SettingsHelper.AppPassword), null);

            string[] scopes     = { "Calendars.Read" };
            var      authResult = await cca.AcquireTokenByAuthorizationCodeAsync(scopes, authCode);

            return(authResult.Token);
        }
コード例 #15
0
        public async Task <AuthResult> GetTokenByAuthCodeAsync(AuthenticationOptions authOptions, string authorizationCode)
        {
            var tokenCache = new AuthTokenCache().GetCacheInstance();
            var client     = new ConfidentialClientApplication(authOptions.ClientId, authOptions.RedirectUrl, new ClientCredential(authOptions.ClientSecret), tokenCache, null);
            var result     = await client.AcquireTokenByAuthorizationCodeAsync(authorizationCode, authOptions.Scopes);

            var authResult = result.ToAuthResult(tokenCache);

            return(authResult);
        }
コード例 #16
0
        public async Task Used_For_ConfidentialClientApplication_Succeeds()
        {
// msal acquiretokenbyauthorizationcodeasync ->
// https://azure.microsoft.com/en-us/resources/samples/active-directory-dotnet-webapp-openidconnect-v2/
// https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Acquiring-tokens-with-authorization-codes-on-web-apps
// app registrations | {confidential client} | api permissions | add a permission | see best practices for requesting permissions ->
// https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-permissions-and-consent

            var app = new ConfidentialClientApplication(confidentialClientId, confidentialClientRedirectUri,
                                                        new ClientCredential(confidentialClientSecret), FileTokenCache.GetUserCache(/* cacheFilePath: "d://temp//my.msalcache.bin", */ cacheFileProtect: false), null);
            //new ClientCredential(confidentialClientSecret), RedisTokenCache.GetAppOrUserCache(uniqueId), null);
            var accounts = await app.GetAccountsAsync();

            AuthenticationResult authResult = null;

            //scopes = new string[] { msftGraphResource };
            //scopes = new string[] { "openid profile offline_access Mail.Read Mail.Send" };

            try
            {
                // attempt to acquire valid token from cache or if expired use refresh token to silently acquire and cache new one
                authResult = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault());
            }
            catch (MsalUiRequiredException ex)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token.
                Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                try
                {
                    authResult = await app.AcquireTokenByAuthorizationCodeAsync(authorizationCode, scopes);

                    //authResult = await app.AcquireTokenOnBehalfOfAsync(scopes, new UserAssertion(accessToken));
                }
                catch (MsalException msalex)
                {
                    // ErrorCode: invalid_grant, StatusCode: 400 implies you need ???
                    // ErrorCode: invalid_scope  StatusCode: 400 implies you need ???
                    Debug.WriteLine($"Error Acquiring Token:{System.Environment.NewLine}{msalex}");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}");
            }

            //var jwt = GetJsonWebToken(authResult.AccessToken); var actual = jwt["body"]["oid"].Value<string>();
            //var jwt = new JwtSecurityTokenHandler().ReadJwtToken(authResult.AccessToken); var actual = jwt.Payload["oid"];
            var actual = authResult.UniqueId;

            var expected = uniqueId;

            Assert.True(actual == expected);
        }
コード例 #17
0
ファイル: MSALAuthProvider.cs プロジェクト: cld0/BotAuth
        public async Task <AuthResult> GetTokenByAuthCodeAsync(AuthenticationOptions authOptions, string authorizationCode)
        {
            InMemoryTokenCacheMSAL        tokenCache = new InMemoryTokenCacheMSAL();
            ConfidentialClientApplication client     = new ConfidentialClientApplication(authOptions.ClientId, authOptions.RedirectUrl,
                                                                                         new ClientCredential(authOptions.ClientSecret), tokenCache);
            Uri redirectUri = new Uri(authOptions.RedirectUrl);
            var result      = await client.AcquireTokenByAuthorizationCodeAsync(authOptions.Scopes, authorizationCode);

            AuthResult authResult = result.FromMSALAuthenticationResult(tokenCache);

            return(authResult);
        }
コード例 #18
0
 /*
  * 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;
     var signedInUserId = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
     var userTokenCache = new MSALSessionCache(signedInUserId,
                                               notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase)
                          .GetMsalCacheInstance();
     var cca = new ConfidentialClientApplication(ClientId, Authority, RedirectUri,
                                                 new ClientCredential(ClientSecret), userTokenCache, null);
     var result = await cca.AcquireTokenByAuthorizationCodeAsync(code, Scopes);
 }
            public void Configure(string name, OpenIdConnectOptions options)
            {
                options.ClientId             = _azureOptions.ClientId;
                options.Authority            = $"{_azureOptions.Instance}common/v2.0";
                options.UseTokenLifetime     = true;
                options.CallbackPath         = _azureOptions.CallbackPath;
                options.RequireHttpsMetadata = false;
                options.ResponseType         = OpenIdConnectResponseType.CodeIdToken;
                var allScopes = $"{_azureOptions.Scopes} {_azureOptions.GraphScopes}".Split(new[] { ' ' });

                foreach (var scope in allScopes)
                {
                    options.Scope.Add(scope);
                }

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                };

                options.Events = new OpenIdConnectEvents
                {
                    //OnTicketReceived = context =>
                    //{
                    //    return Task.CompletedTask;
                    //},
                    OnAuthorizationCodeReceived = async(context) =>
                    {
                        var code        = context.ProtocolMessage.Code;
                        var identifier  = context.Principal.FindFirst(Startup.ObjectIdentifierType).Value;
                        var memoryCache = context.HttpContext.RequestServices.GetRequiredService <IMemoryCache>();
                        var graphScopes = _azureOptions.GraphScopes.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                        var cca = new ConfidentialClientApplication(
                            _azureOptions.ClientId,
                            _azureOptions.BaseUrl + _azureOptions.CallbackPath,
                            new ClientCredential(_azureOptions.ClientSecret),
                            new MemoryCacheTokenCache(identifier, memoryCache).GetCacheInstance(),
                            null);
                        var result = await cca.AcquireTokenByAuthorizationCodeAsync(code, graphScopes);

                        //// 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.Principal.FindFirst(Startup.TenantIdType).Value;
                        //if (currentTenantId == "9188040d-6c67-4c5b-b112-36a304b66dad")
                        //{
                        //    // MSA (Microsoft Account) is used to log in
                        //}

                        context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                    },
                };
            }
コード例 #20
0
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            var code = context.Code;

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

            ConfidentialClientApplication cca =
                new ConfidentialClientApplication(clientId, redirectUri, new ClientCredential(appKey), userTokenCache, null);

            AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, new string[] { scopeWebApi });

            // the result doesn't matter -- our goal is to just populate the TokenCache, which the above call does.
        }
コード例 #21
0
        /// <summary>
        /// Handle authorization codes by creating a token cache then requesting and storing an access token
        /// for the user.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
        {
            string     userId         = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            TokenCache userTokenCache = new SessionTokenCache(
                userId, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
            // A ConfidentialClientApplication is a server-side client application that can securely store a client secret,
            // which is not accessible by the user.
            ConfidentialClientApplication cca = new ConfidentialClientApplication(
                clientId, redirectUri, new ClientCredential(clientSecret), userTokenCache, null);

            string[] scopes = this.scopes.Split(new char[] { ' ' });

            AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(context.Code, scopes);
        }
コード例 #22
0
        public async Task <IActionResult> CallbackAsync(string code, string error, [FromQuery(Name = "error_description")] string description, string resource, string state)
        {
            // アクセス トークンを取得します
            var clientCredential     = new ClientCredential(ClientSecret);
            var clientApplication    = new ConfidentialClientApplication(ClientId, RedirectUrl, clientCredential, null, null);
            var authenticationResult = await clientApplication.AcquireTokenByAuthorizationCodeAsync(code, new[] { Scope });

            // アクセス トークンをセッションに格納します
            var accessToken = authenticationResult.AccessToken;

            this.HttpContext.Session.Set("access_token", Encoding.UTF8.GetBytes(accessToken));

            return(this.RedirectToAction("Index", "Home"));
        }
コード例 #23
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;

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

            var result = await cca.AcquireTokenByAuthorizationCodeAsync(code, B2COptions.ApiScopes.Split(' '));

            context.HandleCodeRedemption(result.AccessToken, result.IdToken);
        }
 private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedContext context)
 {
     // Use MSAL to swap the code for an access token, extract the code from the response notification
     var        code                   = context.ProtocolMessage.Code;
     TokenCache userTokenCache         = new MSALSessionCache(context.HttpContext).GetMsalCacheInstance();
     ConfidentialClientApplication cca = new ConfidentialClientApplication(
         _azureAdB2COptions.ClientId,
         _azureAdB2COptions.Authority,
         _azureAdB2COptions.RedirectUri,
         new ClientCredential(_azureAdB2COptions.ClientSecret),
         userTokenCache,
         null);
     await cca.AcquireTokenByAuthorizationCodeAsync(code, _azureAdB2COptions.VeracityPlatformServiceScopes.Split(' '));
 }
コード例 #25
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                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,
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived = async(context) =>
                    {
                        var code = context.Code;
                        string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                        TokenCache userTokenCache = new SessionTokenCache(
                            signedInUserID,
                            context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase
                            ).GetMsalCacheInstance();
                        ConfidentialClientApplication cca = new ConfidentialClientApplication(
                            appId,
                            redirectUri,
                            new ClientCredential(appSecret),
                            userTokenCache,
                            null);

                        string[] scopes             = graphScopes.Split(new char[] { ' ' });
                        AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);
                    },
                    AuthenticationFailed = (context) =>
                    {
                        context.HandleResponse();
                        context.Response.Redirect("/Error?message=" + context.Exception.Message);
                        return(Task.FromResult(0));
                    }
                }
            }
                );
        }
コード例 #26
0
        public async Task AuthorizationCodeRequestTest()
        {
            TokenCache cache = new TokenCache()
            {
                BeforeAccess = BeforeCacheAccess,
                AfterAccess  = AfterCacheAccess
            };

            ClientCredential cc =
                new ClientCredential("secret");
            var app = new ConfidentialClientApplication(TestConstants.ClientId, "https://" + TestConstants.ProductionEnvironment + "/tfp/home/policy",
                                                        TestConstants.RedirectUri, cc, cache, null)
            {
                ValidateAuthority = false
            };

            //add mock response for tenant endpoint discovery
            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler
            {
                Method          = HttpMethod.Get,
                ResponseMessage = MockHelpers.CreateOpenIdConfigurationResponse(TestConstants.AuthorityHomeTenant, "p=policy")
            });

            HttpMessageHandlerFactory.AddMockHandler(new MockHttpMessageHandler()
            {
                Method          = HttpMethod.Post,
                ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage()
            });

            AuthenticationResult result = await app.AcquireTokenByAuthorizationCodeAsync("some-code", TestConstants.Scope).ConfigureAwait(false);

            Assert.IsNotNull(result);
            Assert.AreEqual(1, app.UserTokenCache.TokenCacheAccessor.AccessTokenCacheDictionary.Count);
            Assert.AreEqual(1, app.UserTokenCache.TokenCacheAccessor.RefreshTokenCacheDictionary.Count);

            cache = new TokenCache()
            {
                BeforeAccess = BeforeCacheAccess,
                AfterAccess  = AfterCacheAccess
            };

            app = new ConfidentialClientApplication(TestConstants.ClientId, "https://" + TestConstants.ProductionEnvironment + "/tfp/home/policy",
                                                    TestConstants.RedirectUri, cc, cache, null)
            {
                ValidateAuthority = false
            };

            Assert.AreEqual(1, app.Users.Count());
        }
        /*
         * 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;

            var userObjectId = notification.AuthenticationTicket.Identity.FindFirst(ObjectIdElement).Value;
            var authority = String.Format(AadInstance, Tenant, DefaultPolicy);
            var httpContext = notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase;

            // Exchange the code for a token. Make sure to specify the necessary scopes
            ClientCredential cred = new ClientCredential(ClientSecret);
            ConfidentialClientApplication app = new ConfidentialClientApplication(authority, Startup.ClientId,
                                                    RedirectUri, cred, new NaiveSessionCache(userObjectId, httpContext));
            var authResult = await app.AcquireTokenByAuthorizationCodeAsync(new string[] { ReadTasksScope, WriteTasksScope }, code, DefaultPolicy);
        }
コード例 #28
0
        /*
         * Callback function when an authorization code is received.
         */
        private static async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
        {
            // Extract the code from the response notification
            var code = notification.Code;

            var authorizationCodeReceived = new AuthorizationCodeReceivedMessage()
            {
                SignedInUserNameIdentifier = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value
            };

            _oidcNotificationHandlerService.OnAuthorizationCodeReceived(authorizationCodeReceived);



            var userTokenCache =
                new MSALSessionCache(
                    authorizationCodeReceived.SignedInUserNameIdentifier,
                    notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase
                    ).GetMsalCacheInstance();

            // TokenCache appTokenCache = null;

            var cca =
                new ConfidentialClientApplication(
                    _ib2COidcConfidentialClientSettingsConfiguration.ClientId,
                    _ib2COidcConfidentialClientSettingsConfiguration.AuthorityUri,      // "https://login.microsoftonline.com/tfp/{tenantAuthorityName}/{defaultPolicyId}/v2.0/.well-known/openid-configuration"
                    _ib2COidcConfidentialClientSettingsConfiguration.ClientRedirectUri, // eg: "https://localhost:44311"
                    new ClientCredential(_ib2COidcConfidentialClientSettingsConfiguration.ClientSecret),
                    userTokenCache,
                    null);


            try
            {
                AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, _fullyQualifiedScopesRequiredByTargetApi);

                // this is actually wrong
                //if (result.Scopes != null && result.Scopes.Any())
                //{
                //    notification.AuthenticationTicket.Identity.AddClaim(new Claim(Infrastructure.Constants.IDA.ClaimTitles.ScopeElementId, string.Join(" ", result.Scopes).TrimEnd()));
                //}
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                throw;
            }
        }
        public override async Task Invoke(IOwinContext context)
        {
            string code = context.Request.Query["code"];

            if (code != null)
            {
                //extract state
                string state         = HttpUtility.UrlDecode(context.Request.Query["state"]);
                string session_state = context.Request.Query["session_state"];

                string          signedInUserID    = context.Authentication.User.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
                HttpContextBase hcb               = context.Environment["System.Web.HttpContextBase"] as HttpContextBase;
                TokenCache      userTokenCache    = new MSALSessionCache(signedInUserID, hcb).GetMsalCacheInstance();
                ConfidentialClientApplication cca = new ConfidentialClientApplication(options.ClientId, options.RedirectUri, new ClientCredential(options.ClientSecret), userTokenCache, null);

                //validate state

                CodeRedemptionData crd = OAuth2RequestManager.ValidateState(state, hcb);

                if (crd != null)
                {
                    //If Valid redeem code

                    try
                    {
                        AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, crd.Scopes);
                    }
                    catch (Exception ex)
                    {
                        context.Response.Write(ex.Message);
                    }

                    //redirect to original requestor

                    context.Response.StatusCode = 302;
                    context.Response.Set("Location", crd.RequestOriginatorUrl);
                }
                else
                {
                    context.Response.StatusCode = 302;
                    context.Response.Set("Location", "/Error?message" + "code_redeem_failed");
                }
            }
            else
            {
                await this.Next.Invoke(context);
            }
        }
コード例 #30
0
        private async Task OnAuthorization(AuthorizationCodeReceivedNotification context)
        {
            var        code                   = context.Code;
            string     signedInUserId         = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
            TokenCache userTokenCache         = new MSALSessionCache(signedInUserId, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
            ConfidentialClientApplication cca = new ConfidentialClientApplication(clientId, redirectUri, new ClientCredential(appKey), userTokenCache, null);

            string[] scopes = { "Mail.Read" };
            try
            {
                AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, scopes);
            }
            catch (Exception ex) {
                context.Response.Write(ex.Message);
            }
        }