VS2022中的官方方案中,鉴权方案会用到SqlServer,而我的项目要用MySql,两者没法兼容,遂自己写了一套。
预备:用VS2022新建一个Blazor Server项目
?
第一步:编写自定义的登录,退出,鉴权类?SessionObjectHelper.cs,并且在Program.cs里注册
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
namespace BlazorAppAuthDemo
{
public class SessionObjectHelper
{
private ProtectedSessionStorage _sessionStorage;
public SessionObjectHelper(ProtectedSessionStorage storage)
{
_sessionStorage = storage;
}
/// <summary>
/// 是否登录
/// </summary>
/// <returns></returns>
public async Task<bool> IsLogin()
{
var value = await _sessionStorage.GetAsync<string>("user");
if (value.Success && !string.IsNullOrEmpty(value.Value))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 是否有权限
/// </summary>
/// <returns></returns>
public async Task<bool> HasAuth(string authString)
{
var value = await _sessionStorage.GetAsync<string>("user");
if (value.Success && !string.IsNullOrEmpty(value.Value))
{
if (!string.IsNullOrEmpty(authString) && authString.Equals(value.Value))
{
return true;
}
return false;
}
else
{
return false;
}
}
public async Task<string> GetSession()
{
var value = await _sessionStorage.GetAsync<string>("user");
return value.Success?value.Value:"";
}
public async Task SetSession(string value)
{
await _sessionStorage.SetAsync("user", value);
}
/// <summary>
/// 设置过期
/// </summary>
/// <returns></returns>
public async Task SetExpires()
{
await _sessionStorage.SetAsync("user", "");
}
}
}
在Program.cs里注册?
builder.Services.AddScoped<SessionObjectHelper>();
?
第二步:自定义鉴权的控件?AuthComponet.razor
@using BlazorAppAuthDemo.Data
@inject SessionObjectHelper Session
@if (Logined)
{
@if (doNotReload)
{
<p>出现错误,请点此刷新</p>
}
else
{
@if (HasAuth)
{
<CascadingValue Value="@this">
@ChildContent
</CascadingValue>
}
else
{
<p>暂无权限查看...</p>
}
}
}
else
{
<p>尚未登录,请先 <a href="/login">登录</a></p>
}
@code {
public bool Logined;
public bool HasAuth;
private bool doNotReload;
[Parameter]
public RenderFragment ChildContent { get; set; }
[Inject]
NavigationManager Navigation { get; set; }
[Parameter]
public string AuthString { get; set; }
public string UserAuths { get; set; }
protected override async Task OnInitializedAsync()
{
try
{
if (await Session.IsLogin())
{
Logined = true;
if (await Session.HasAuth(AuthString))
{
HasAuth = true;
}
}
}
catch (Exception ex)
{
doNotReload = true;
//Navigation.NavigateTo("/", true, true);
}
}
}
第三步:使用
1、登录页面Login.razor及方法使用
@page "/Login"
@inject SessionObjectHelper Session
<h3>登录</h3>
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await Session.SetSession("abc");
await base.OnAfterRenderAsync(firstRender);
}
}
2、退出登录页面Logout.razor及方法使用
@page "/Logout"
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject SessionObjectHelper Session
<h3>Logout</h3>
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await Session.SetSession(null);
await base.OnAfterRenderAsync(firstRender);
}
}
3、鉴权页面Counter.razor及方法使用
@page "/counter"
@using BlazorAppAuthDemo.Data
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
<span>是否登录 @(IsLogin)</span>
<span>是否是否有权限 @(HasAuth)</span>
<AuthComponet>
<span>哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈</span>
</AuthComponet>
@code {
private bool IsLogin{ get; set; }
private bool HasAuth{ get; set; }
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
[Inject]
public SessionObjectHelper Session { get; set; } = default;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
IsLogin = await Session.IsLogin();
HasAuth = await Session.HasAuth("sdef");
this.StateHasChanged();
}
await base.OnAfterRenderAsync(firstRender);
}
}
最后:验证效果
点击Counter页面,会发现有未登录和没有权限的提示
?
手动改URL为:BlazorAppAuthDemohttp://localhost:2254/login
自己玩吧:)
|