简体   繁体   中英

SIgn-in error in .NET 6 web application using Microsoft Identity (aka: Azure Active Directory)

I'm trying to use Microsoft Identity (formerly: Azure AD) authentication in an ASP.NET web application running on .NET 6

I've used this code to configure authentication in my startup class ConfigureServices method:

    services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(options => {
            options.Instance = appSettings.UserSettings.AzIdInstance;
            options.Domain = appSettings.UserSettings.AzIdDomain;
            options.TenantId = appSettings.UserSettings.AzIdTenantId;
            options.ClientId = appSettings.UserSettings.AzIdClientId;
            options.CallbackPath = appSettings.UserSettings.AzIdCallbackPath;
            options.SignedOutCallbackPath = appSettings.UserSettings.AzIdSignOutCallbackPath;
        });
    services.AddAuthorization();

Then in the Configure method, I've added:

app.UseAuthentication();
app.UseAuthorization();

When I try to access a controller action protected by the [Authorize] attribute, it correctly redirects me to the microsoft login page, however after I log in when the app then tries to redirect to my callback path ( /signin-oidc ) the connection gets reset and I get this browser error:

在此处输入图像描述

What am I doing wrong here? Is there a good example online on how to properly configure this?

Apparently, this error was happening because I had set the cookie's SameSite attribute to None with this code (I need it to be None for some cross-domain calls that are done to the server):

services.Configure<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
    //In-memory cookie store, so sessions are forcibly killed when the webapp restarts
    //This ensures that the user's Claims are up to date - remember to restart the service when Azure AD security group memberships are changed!
    options.SessionStore = services.BuildServiceProvider().GetService<MemoryCacheTicketStore>();

    //We want to disable the same-site policy, otherwise cross-domain API calls from JS won't work
    options.Cookie.SameSite = SameSiteMode.None;
});

apparently this by itself causes the error. To fix it, I had to also add the following code:

services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.HandleSameSiteCookieCompatibility(s => false);
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

this seems to have fixed the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM