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 @ 2024-09-17 16:04  known  阅读(62)  评论(0编辑  收藏  举报