ils*_*ker 9 .net jwt .net-core jwt-auth blazor-server-side
我想了解,如何为Blazor 服务器端应用程序设置JWT 身份验证?
让我举一个例子:假设我们有一个 .NET Core 3.1 Web API 项目。该项目有自己的TokenController实现,它为有效的用户/密码组合提供 JWT。所有其他控制器对每个请求都需要这样的令牌。
验证身份验证的中间件配置如下:
// enabling JWT bearer scheme
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
// TOKEN VALIDATION PARAMETERS
};
});
// applying default authentication policy
services.AddMvc(o =>
{
o.EnableEndpointRouting = false;
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
o.Filters.Add(new AuthorizeFilter(policy));
}).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
Run Code Online (Sandbox Code Playgroud)
到这里为止,这工作得很好。
现在我想为这个项目添加一个漂亮的 Blazor 服务器端 UI,但我无法思考如何进行身份验证?
根据 Microsoft Docs,服务器端应用程序的身份验证应该在建立 SignalR 连接时进行:
Blazor 服务器身份验证
Blazor 服务器应用通过使用 SignalR 创建的实时连接运行。在建立连接时处理基于 SignalR 的应用程序中的身份验证。身份验证可以基于 cookie或其他一些不记名令牌。
(来源:https : //docs.microsoft.com/en-us/aspnet/core/security/blazor/?view=aspnetcore-3.1&tabs=visual-studio)
不幸的是,我无法弄清楚这是如何工作的 - 我找到的教程和技巧要么是针对客户端 Blazor 的,要么是使用 Cookie / Identity ...
有任何想法吗?
我设置了带有身份验证的 Blazor 服务器,然后为 API 添加了 JWT 身份验证。所以我认为反过来也是一样的。
这就是我所做的:
ConfigureServices方法(我认为顺序可能很重要,不确定):
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
// not sure if this line is required for Blazor auth
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
services.AddAuthentication()
.AddCookie(cfg => cfg.SlidingExpiration = true)
.AddJwtBearer(x =>
{
// options
});
Run Code Online (Sandbox Code Playgroud)
// SamplePage.razor.cs
[Route("page-path")]
[Authorize]
public partial class SamplePage
{ }
// or like this in SamplePage.razor
@page "page-path"
@attribute [Authorize]
Run Code Online (Sandbox Code Playgroud)
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class SampleController : ControllerBase
{ }
Run Code Online (Sandbox Code Playgroud)
在我开始使用 Blazor 服务器端项目后,我发现此页面中的内容对于让 JWT 工作非常有帮助。https://jasonwatmore.com/post/2019/10/11/aspnet-core-3-jwt-authentication-tutorial-with-example-api
| 归档时间: |
|
| 查看次数: |
4996 次 |
| 最近记录: |