Blazor(交互式服务器)cookie 身份验证:从 Razor 页面进行 LocalRedirect 后,用户身份会丢失

问题描述 投票:0回答:1

我有一个 Blazor 服务器应用程序,它依赖第三方 Rest API 对用户进行身份验证,提供可用于任何 HTTP 调用的令牌。 Blazor 方面我实现了一个自定义身份验证状态提供程序来管理用户状态,一切正常。 现在我需要实现两个内部控制器(在同一个项目中,我正在使用的某些组件库需要它们),这样它们就不安全,所以我试图通过基于 Cookie 的身份验证。

我设法将 cookie 存储在浏览器中,据我所知,cookie 正在请求中发送到 Razor 组件。但是,如果页面标有

[Authroize]
属性(它们都是),我只是被设计重定向到登录页面。 仔细检查后,我发现一旦我从用于访问 HttpContext 的 Razor 页面重定向到 Blazor 组件,用户身份就完全丢失了(因此
authenticationState.User.Identity.IsAuthenticated
始终是
false
)。

我已经阅读了很多帖子和文档,但我真的不明白为什么。我提供一些简化的代码。感谢您的任何提示。

LoginAuth.cshtml


public async Task<IActionResult> OnGetAsync(string u) {


     var claims = new List<Claim>
     {
         new Claim(ClaimTypes.Name, u),
     };
    
     var claimsIdentity = new ClaimsIdentity(
         claims, CookieAuthenticationDefaults.AuthenticationScheme);
    
     var authProperties = new AuthenticationProperties
     {
         IsPersistent = true,
     };
    
     await HttpContext.SignInAsync(
         CookieAuthenticationDefaults.AuthenticationScheme,
         new ClaimsPrincipal(claimsIdentity),
         authProperties);
    return LocalRedirect("/dashboard");
}

登录.razor

 private async Task Authenticate()
   {
       var result = await authenticationService.GetToken(user);
          if (result != null) {
    //storing some info inside session storage and updating the auth. state (this should be removed
//with a working Cookie auth i guess)
                             }
       navManager.NavigateTo($"/loginAuth?u={result.Username}",true);


   }

程序.cs

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(20);  
        options.SlidingExpiration = true;
        options.LoginPath = "/login";
        options.Cookie.HttpOnly = true;  
        options.Cookie.SameSite = SameSiteMode.Lax;  
        options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
    });
c# authentication cookies blazor-server-side httpcontext
1个回答
0
投票

我发现了问题:我之前使用的是 CustomAuthenticationStateProvider,但我忘记将其从应用程序生成器中删除:

builder.Services.AddScoped<AuthenticationStateProvider, CustomAuthenticationStateProvider>();

正如我猜测的那样,这会覆盖来自不同身份验证流程的任何其他状态。

© www.soinside.com 2019 - 2024. All rights reserved.