简体   繁体   English

ASP.NET 浏览器关闭后核心身份验证未保持登录状态(Azure AD B2C)

[英]ASP.NET Core Auth not staying signed in after browser closes (Azure AD B2C)

I've successful set up authentication with Azure AD B2C in my ASP.NET Core Blazor application.我已经在我的 ASP.NET Core Blazor 应用程序中成功设置了 Azure AD B2C 的身份验证。 I can open the website (https://localhost:5001) in multiple tabs without signing in again.我可以在多个选项卡中打开网站 (https://localhost:5001) 而无需再次登录。 However, if I keep the server running but close and reopen the browser and navigate to the website, it requires me to sign in again.但是,如果我保持服务器运行但关闭并重新打开浏览器并导航到该网站,则需要我再次登录。 My understanding was that it should have kept me signed in between browser sessions.我的理解是它应该让我在浏览器会话之间保持登录状态。 I'm fairly new to all this, so I'm not even sure where to begin looking for the problem.我对这一切都很陌生,所以我什至不确定从哪里开始寻找问题。 Any ideas what this might be?任何想法这可能是什么?

Here is my Startup.cs , if it helps.这是我的Startup.cs ,如果有帮助的话。

public class Startup
{
    private IConfiguration Configuration { get; }
        
    public Startup(IConfiguration configuration) => Configuration = configuration;

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAdB2C"));
            
        services.AddControllersWithViews().AddMicrosoftIdentityUI();

        services.AddAuthorization(options =>
        {
            // By default, all incoming requests will be authorized according to the default policy
            options.FallbackPolicy = options.DefaultPolicy;
        });
            
        services.AddRazorPages();
        services.AddServerSideBlazor().AddMicrosoftIdentityConsentHandler();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/_Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

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

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });
    }

I found the solution to my problem.我找到了解决我的问题的方法。 Thanks to @huysentruitw for putting me on the right path.感谢@huysentruitw让我走上了正确的道路。

TL;DR: Creating my own AccountController and setting AuthenticationProperties.IsPersistent to true on sign in fixed the expiration of the auth cookie and ultimately solved my problem. TL;DR:创建我自己的AccountController并在登录时将AuthenticationProperties.IsPersistent设置为true修复了身份验证 cookie 的过期问题,最终解决了我的问题。

The problem was basically that the auth token cookie was not being persisted across browser sessions.问题基本上是身份验证令牌cookie没有在浏览器会话中保留。 It would always create the cookie, but looking in DevTools, the expiration was always set to "Session".它总是会创建 cookie,但在 DevTools 中查看,过期总是设置为“Session”。 However, configuring the expire times via the options available in Startup.cs didn't resolve it either.但是,通过Startup.cs中可用的选项配置过期时间也没有解决它。 I tried the following:我尝试了以下方法:

  • Setting it via ConfigureApplicationCookie with CookieAuthenticationOptions.Cookie.Expires .通过ConfigureApplicationCookieCookieAuthenticationOptions.Cookie.Expires设置它。
  • Setting it via ConfigureApplicationCookie with CookieAuthenticationOptions.ExpireTimeSpan通过ConfigureApplicationCookieCookieAuthenticationOptions.ExpireTimeSpan设置它
  • Setting it via .AddMicrosoftIdentityWebApp using the overload to provide configureCookieAuthenticationOptions with a CookieBuilder.Expires property populated.通过.AddMicrosoftIdentityWebApp使用重载设置它,以提供configureCookieAuthenticationOptions并填充CookieBuilder.Expires属性。
  • A few other obscure things that I didn't expect to work anyway, but I was looking for anything to work.其他一些我没想到会起作用的晦涩难懂的东西,但我一直在寻找可以起作用的东西。

No matter what I did, the cookie came through as expiring after the "Session".无论我做什么,cookie 在“会话”之后过期。

So, I stepped into the ASP.Net Core authentication code (the CookieAuthenticationHandler class in Microsoft.AspNetCore.Authentication.Cookies ) to find out why the expiration value wasn't being used.因此,我进入了 ASP.Net Core 身份验证代码( Microsoft.AspNetCore.Authentication.Cookies中的CookieAuthenticationHandler class )以找出未使用到期值的原因。 I found that CookieOptions.Expires is overridden for some reason (in the BuildCookieOptions method) and that the expiry is only set if AuthenticationProperties.IsPersistent is true (you can see this happening in HandleSignInAsync method).我发现CookieOptions.Expires出于某种原因(在BuildCookieOptions方法中)被覆盖,并且仅在AuthenticationProperties.IsPersistenttrue时才设置到期(您可以在HandleSignInAsync方法中看到这种情况)。 So, my next step was to figure out how to set that to true.因此,我的下一步是弄清楚如何将其设置为 true。 I found that the AuthenticationProperties are set by an AccountController that is added automatically by the call in Startup.cs to .AddMicrosoftIdentityUI .我发现AuthenticationProperties是由AccountController设置的,该 AccountController 由Startup.cs中的调用自动添加到.AddMicrosoftIdentityUI I copied this AccountController to my project as a starting point instead and got rid of the call to .AddMicrosoftIdentityUI .我将此AccountController复制到我的项目中作为起点,并摆脱了对.AddMicrosoftIdentityUI的调用。 I then updated the AuthenticationProperties to set IsPersistent to true , which is ultimated what fixed the issue.然后我更新了AuthenticationProperties以将IsPersistent设置为true ,这最终解决了这个问题。 The cookie now comes through with an expiration date/time. cookie 现在带有过期日期/时间。

I don't know if I missed something, but it certainly seems like a bug to me, or at least a really poor configuration experience.我不知道我是否遗漏了什么,但这对我来说肯定是一个错误,或者至少是一个非常糟糕的配置体验。 Hopefully someone will come along and potentially point out my blunder, but this is what worked for me.希望有人会出现并可能指出我的错误,但这对我有用。 I think it makes more sense to pull the AccountController into my project anyway so that I can see what's going on and fine tune it as needed.我认为无论如何将AccountController拉入我的项目更有意义,这样我就可以看到正在发生的事情并根据需要对其进行微调。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core 3.1 和 Azure AD B2C 与外部身份提供者身份验证 - invalid_request - ASP.NET Core 3.1 and Azure AD B2C with external Identity Providers auth - invalid_request 使用ASP.NET Core的Azure AD B2C - 无法编辑配置文件 - Azure AD B2C with ASP.NET Core - Unable to go to edit profile 跨 ASP.Net Core Web 应用程序使用 Azure AD B2C Cookie - Use Azure AD B2C Cookie across ASP.Net Core Web Apps ASP.NET Core 3.1 如何使用 Azure AD B2C 返回 401 Unauthorized 而不是 Challenge - ASP.NET Core 3.1 how to return 401 Unauthorized instead of Challenge with Azure AD B2C 无法使用 asp.net 核心图 API 在 Azure AD B2C 中创建自定义属性 - Can't create custom attributes in Azure AD B2C with asp.net core Graph API 使用 Azure AD B2C 使用个人用户帐户登录 ASP.Net Core Web 应用程序 -> API - Sign in to ASP.Net Core Web Application -> API with Individual User Accounts using Azure AD B2C 如何从 Azure AD B2C 用户商店获取 ASP.NET Core 3.1 中的用户信息? - How to get user information in ASP.NET Core 3.1 from Azure AD B2C user store? ASP.NET Core:Azure AD B2C自助密码重置(注册/登录策略) - ASP.NET Core: Azure AD B2C self service password reset (sign-up/sign-in policy) 一个使用 Azure AD B2C 的多个客户端 ID(应用程序 ID)的 ASP.NET Core 2.2 Web API 应用程序 - One ASP.NET Core 2.2 Web API app Using Multiple Client IDs (Application IDs) of Azure AD B2C 无法使用来自我的 asp.net 核心 web 应用程序的 AAD B2C 中的自定义策略登录多租户 Azure AD - unable to sign In for MultiTenant Azure AD using Custom policies in AAD B2C from my asp.net core web app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM