コード例 #1
0
            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
                {
                    // Ensure that User.Identity.Name is set correctly after login
                    NameClaimType = "name",

                    // Instead of using the default validation (validating against a single issuer value, as we do in line of business apps),
                    // we inject our own multitenant validation logic
                    ValidateIssuer = false,

                    // If the app is meant to be accessed by entire organizations, add your issuer validation logic here.
                    //IssuerValidator = (issuer, securityToken, validationParameters) => {
                    //    if (myIssuerValidationLogic(issuer)) return issuer;
                    //}
                };

                options.Events = new OpenIdConnectEvents
                {
                    OnTicketReceived = context =>
                    {
                        // If your authentication logic is based on users then add your logic here
                        return(Task.CompletedTask);
                    },
                    OnAuthenticationFailed = context =>
                    {
                        context.Response.Redirect("/Home/Error");
                        context.HandleResponse(); // Suppress the exception
                        return(Task.CompletedTask);
                    },
                    OnAuthorizationCodeReceived = async(context) =>
                    {
                        string code = context.ProtocolMessage.Code;
                        // Get access token using authorization code
                        AuthenticationResult result = await _authProvider.GetUserAccessTokenByAuthorizationCode(code);

                        context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                    },
                    // If your application needs to do authenticate single users, add your user validation below.
                    //OnTokenValidated = context =>
                    //{
                    //    return myUserValidationLogic(context.Ticket.Principal);
                    //}
                };
            }
            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
                {
                    // Ensure that User.Identity.Name is set correctly after login
                    NameClaimType = "name",

                    // Instead of using the default validation (validating against a single issuer value, as we do in line of business apps),
                    // we inject our own multitenant validation logic
                    ValidateIssuer = false,

                    // If the app is meant to be accessed by entire organizations, add your issuer validation logic here.
                    //IssuerValidator = (issuer, securityToken, validationParameters) => {
                    //    if (myIssuerValidationLogic(issuer)) return issuer;
                    //}
                };

                options.Events = new OpenIdConnectEvents
                {
                    OnTicketReceived = context =>
                    {
                        // If your authentication logic is based on users then add your logic here
                        return(Task.CompletedTask);
                    },
                    OnAuthenticationFailed = context =>
                    {
                        context.Response.Redirect("/Home/Error");
                        context.HandleResponse(); // Suppress the exception
                        return(Task.CompletedTask);
                    },
                    OnAuthorizationCodeReceived = async(context) =>
                    {
                        var code       = context.ProtocolMessage.Code;
                        var identifier = context.Principal.FindFirst(Startup.ObjectIdentifierType).Value;

                        var result = await _authProvider.GetUserAccessTokenByAuthorizationCode(code);

                        // 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);
                    },
                    // If your application needs to do authenticate single users, add your user validation below.
                    //OnTokenValidated = context =>
                    //{
                    //    return myUserValidationLogic(context.Ticket.Principal);
                    //}
                };
            }
コード例 #3
0
            public void Configure(string name, OpenIdConnectOptions options)
            {
                options.ClientId             = _azureOptions.ClientId;
                options.ClientSecret         = _azureOptions.ClientSecret;
                options.Authority            = $"{_azureOptions.Instance}{_azureOptions.TenantId}/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
                {
                    NameClaimType = "name",

                    // Instead of using the default validation (validating against a single issuer value, as we do in line of business apps),
                    // we inject our own multitenant validation logic
                    ValidateIssuer = false,

                    // If the app is meant to be accessed by entire organizations, add your issuer validation logic here.
                    //IssuerValidator = (issuer, securityToken, validationParameters) => {
                    //    if (myIssuerValidationLogic(issuer)) return issuer;
                    //}
                };

                options.Events = new OpenIdConnectEvents
                {
                    OnTicketReceived = context =>
                    {
                        // If your authentication logic is based on users then add your logic here
                        return(Task.CompletedTask);
                    },
                    OnAuthenticationFailed = context =>
                    {
                        string redirectUrl = $"/Home/Error?msg={System.Net.WebUtility.UrlEncode(context.Exception.Message)}";
                        if (context.Exception is Microsoft.Identity.Client.MsalServiceException)
                        {
                            var svcExp = context.Exception as Microsoft.Identity.Client.MsalServiceException;
                            if (svcExp.ErrorCode == "invalid_grant")
                            {
                                redirectUrl = "/Account/PermissionsRequired";
                            }
                        }

                        if (context.Exception is Microsoft.Identity.Client.MsalUiRequiredException)
                        {
                            var svcExp = context.Exception as Microsoft.Identity.Client.MsalUiRequiredException;
                            if (svcExp.ErrorCode == "invalid_grant")
                            {
                                redirectUrl = "/Account/PermissionsRequired";
                            }
                        }

                        context.Response.Redirect(redirectUrl);
                        context.HandleResponse(); // Suppress the exception
                        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 redirectUri = _azureOptions.BaseUrl + _azureOptions.CallbackPath;

                        //var cca = new ConfidentialClientApplication(
                        //    _azureOptions.ClientId,
                        //    redirectUri,
                        //    new ClientCredential(_azureOptions.ClientSecret),
                        //    new InMemoryTokenCache(identifier, memoryCache).GetCacheInstance(),
                        //    null);
                        var result = await _authProvider.GetUserAccessTokenByAuthorizationCode(code);

                        // 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);
                    },
                    // If your application needs to do authenticate single users, add your user validation below.
                    //OnTokenValidated = context =>
                    //{
                    //    return myUserValidationLogic(context.Ticket.Principal);
                    //}
                };
            }