本文介绍 Blazor 静态服务端呈现(静态 SSR)模式下,用户登录身份认证是如何实现的。
SSR 是服务器侧呈现,HTML 是由服务器上的 ASP.NET Core 运行时生成,通过网络发送到客户端,供客户端的浏览器显示。SSR 分两种类型:
由于交互式 SSR 存在断线重连的问题,影响用户体验,所以采用静态 SSR 组件呈现服务端内容,为了增加前端交互体验,采用 JavaScript 作为前端交互。
public class UserInfo
{
public string UserName { get; set; }
}
public class Context
{
public UserInfo CurrentUser { get; set; }
}
<!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;
}
}
<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();
}
}
@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; }
}
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);
}
}