【发布时间】:2019-03-20 18:28:40
【问题描述】:
我尝试按照本教程 (http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/4316/A-Demonstration-of-Simple-Server-side-Blazor-Cookie-Authentication.aspx) 使用 ASP.NET Core 3.0 和 Blazor 框架 v.0.9.0(最新版本)制作具有 cookie 身份验证的应用程序。对于 IDE,我使用的是 VS 2019 Preview。
作者使用早期版本的 Blazor,但我按照教程使用客户端项目而不是应用程序,因为我认为它们做同样的事情,只是在不同版本的 Blazor 中调用不同。
这是我的结果的回购链接:https://github.com/SaintMSent/TestBlazorCookieAuth
问题是,它不起作用。如果我转到 localhost:port/login 页面,则会创建 cookie(我检查了 Chrome 开发工具)。如果我去注销页面,它会被删除,所以这部分很好。但该应用程序的其他页面不会加载。如果我从 MainLayout 中删除 Login 组件,一切都加载正常,所以我认为问题在于 Login.cshtml 中的 HttpContext 和 HttpContextAccessor
这是 Login.cshtml 的样子
@using System.Security.Claims
@using Microsoft.AspNetCore.Http
@page "/login"
@inject IHttpContextAccessor _httpContextAccessor
@inject HttpClient Http
@if (User.Identity.Name != null)
{
<b>You are logged in as: @User.Identity.Name</b>
<a class="ml-md-auto btn btn-primary"
href="/logout?returnUrl=/"
target="_top">Logout</a>
}
else
{
<a class="ml-md-auto btn btn-primary"
href="/login?returnUrl=/"
target="_top">Login</a>
}
@functions {
private ClaimsPrincipal User;
protected override void OnInit()
{
base.OnInit();
try
{
// Set the user to determine if they are logged in
User = _httpContextAccessor.HttpContext.User;
}
catch { }
}
}
请帮我弄清楚这里发生了什么。我希望我提供了足够的详细信息,谢谢。
更新:如果我添加这一行
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
到 Client 项目中的 Startup.cs,一切都在加载,但 _httpContextAccessor.HttpContext.User 始终为空
【问题讨论】:
-
“使用客户端项目而不是应用程序” - cookie 是服务器的东西(浏览器只是保存它们)。此方法仅适用于服务器端 Blazor。
-
"IHttpContextAccessor 可用于访问当前线程的 HttpContext"。我不确定你可以这样使用它。使用 JWT 进行身份验证。
-
@if (User.Identity.Name != null){} 这很糟糕...您必须检查用户是否经过身份验证。
-
if (User.Identity.IsAuthenticated) { ------- } else { ------- }
-
@HenkHolterman 教程作者在服务器项目中有登录和注销页面,但在客户端项目中访问 HttpContextAccessor 并且效果很好,我下载了他的示例,它确实有效
标签: c# asp.net asp.net-core blazor razor-components