using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
using System.Security.Claims;
namespace BSAuth.Auth
{
public class Provider : AuthenticationStateProvider
{
private readonly ProtectedSessionStorage _sessionStorage;
private readonly ClaimsPrincipal _anonymous = new ClaimsPrincipal(new ClaimsIdentity());
public Provider(ProtectedSessionStorage sessionStorage)
{
_sessionStorage = sessionStorage;
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
try
{
var userSessionStorageResult = await _sessionStorage.GetAsync<UserSession>("UserSession");
var userSession = userSessionStorageResult.Success ? userSessionStorageResult.Value : null;
if (userSession == null)
{
return await Task.FromResult(new AuthenticationState(_anonymous));
}
var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.Name,userSession.UserName),
new Claim(ClaimTypes.Role,userSession.Role)
}, "customAuth")); ;
return await Task.FromResult(new AuthenticationState(claimsPrincipal));
}
catch
{
return await Task.FromResult(new AuthenticationState(_anonymous));
}
}
public async Task UpdateAuthState(UserSession userSession)
{
ClaimsPrincipal claimsPrincipal;
if (userSession is not null)
{
await _sessionStorage.SetAsync("UserSession", userSession);
claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new List<Claim>
{
new Claim(ClaimTypes.Name,userSession.UserName),
new Claim(ClaimTypes.Role,userSession.Role)
}));
}
else
{
await _sessionStorage.DeleteAsync("UserSession");
claimsPrincipal = _anonymous;
}
NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(claimsPrincipal)));
}
}
}
创建 UserSession 模型和 UserAccount 模型
namespace BSAuth.Auth
{
public class UserSession
{
public string UserName { get; set;}
public string Role { get; set;}
}
}
namespace BSAuth.Auth
{
public class UserAccount
{
public string UserName { get; set; }
public string Password { get; set; }
public string Role { get; set; }
}
}
然后建立账户系统服务,这里Demo用的内存数据模拟,实际应该使用数据库
namespace BSAuth.Auth
{
public class UserAccountService
{
private List<UserAccount> _user;
public UserAccountService()
{
_user = new List<UserAccount>
{
new UserAccount{UserName="张三",Password="zs",Role="admin"},
new UserAccount{UserName="李四",Password="ls",Role="user"}
};
}
public UserAccount? GetByUserName(string userName)
{
return _user.FirstOrDefault(x => x.UserName == userName);
}
}
}