Blazor静态服务端呈现(静态SSR)身份认证

本文介绍 Blazor 静态服务端呈现(静态 SSR)模式下,用户登录身份认证是如何实现的。

1. SSR 简介

SSR 是服务器侧呈现,HTML 是由服务器上的 ASP.NET Core 运行时生成,通过网络发送到客户端,供客户端的浏览器显示。SSR 分两种类型:

  • 静态 SSR:服务器生成静态 HTML,它不提供用户交互性或维护 Razor 组件状态,通过 HTTP 协议进行通信。
  • 交互式 SSR:Blazor 事件允许用户交互,并且 Razor 组件状态由 Blazor 框架维护,通过 SignalR 连接使用 WebSocket 协议进行通信。

2. 为什么用静态 SSR

由于交互式 SSR 存在断线重连的问题,影响用户体验,所以采用静态 SSR 组件呈现服务端内容,为了增加前端交互体验,采用 JavaScript 作为前端交互。

3. 实现思路

  • 在 App.razor 文件中使用级联参数的 HttpContext 对象获取用户是否登录
  • 将用户登录信息传递给路由组件的级联 Context 对象,
  • 在所有子组件中,使用级联参数的 Context 对象获取用户信息
  • 使用 HttpContext.SignInAsync 和 HttpContext.SignOutAsync 实现登录和注销

4. 实现步骤

  • 创建 UserInfo 和 Context 类
public class UserInfo
{
public string UserName { get; set; }
}
public class Context
{
public UserInfo CurrentUser { get; set; }
}
  • 创建 App.razor 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<Routes User="user" />
</body>
</html>
@code {
[CascadingParameter] private HttpContext HttpContext { get; set; }
private UserInfo user;
protected override void OnInitialized()
{
base.OnInitialized();
if (HttpContext.User.Identity.IsAuthenticated)
user = new UserInfo { UserName = HttpContext.User.Identity.Name };
else
user = null;
}
}
  • 创建 Route.razor 文件
<CascadingValue Value="context" IsFixed>
<Router AppAssembly="typeof(Program).Assembly">
<Found Context="routeData">
<RouteView RouteData="routeData" />
</Found>
<NotFound></NotFound>
</Router>
</CascadingValue>
@code {
private UIContext context;
[Parameter] public UserInfo User { get; set; }
protected override void OnInitialized()
{
context = new Context();
context.CurrentUser = User;
base.OnInitialized();
}
}
  • 创建 LoginBox.razor 文件
@if (Context.CurrentUser == null)
{
<span onclick="login()">登录</span>
<script>
function login() { fetch('/signin').then(res => location.reload()); }
</script>
}
else
{
<span onclick="logout()">退出</span>
<script>
function logout() { fetch('/signout').then(res => location.reload()); }
</script>
}
@code {
[CascadingParameter] private Context Context { get; set; }
}
  • 创建 AuthController.cs 文件
public class AuthController : ControllerBase
{
private const string AuthType = "App_Cookie";
[Route("signin")]
public async Task Login([FromBody] UserInfo info)
{
var claims = new List<Claim>() { new(ClaimTypes.Name, info.UserName) };
var identity = new ClaimsIdentity(claims, AuthType);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(AuthType, principal);
}
[Route("signout")]
public async Task Logout()
{
await HttpContext.SignOutAsync(AuthType);
}
}
posted @   known  阅读(491)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
历史上的今天:
2023-09-17 Blazor前后端框架Known-V1.2.15
点击右上角即可分享
微信分享提示