TheProvider.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using EasyTemplate.Service;
  2. using EasyTemplate.Tool;
  3. using Microsoft.AspNetCore.Components.Authorization;
  4. using System.Security.Claims;
  5. namespace EasyTemplate.Blazor.Web.Common;
  6. public class CustomAuthenticationStateProvider : AuthenticationStateProvider
  7. {
  8. /// <summary>
  9. ///
  10. /// </summary>
  11. private NavigationManager _NavigationManager;
  12. /// <summary>
  13. ///
  14. /// </summary>
  15. private ClaimsIdentity identity { get; set; } = new ClaimsIdentity();
  16. public CustomAuthenticationStateProvider(NavigationManager NavigationManager)
  17. {
  18. _NavigationManager = NavigationManager;
  19. }
  20. /// <summary>
  21. /// 用户认证成功,创建用户的ClaimsIdentity
  22. /// </summary>
  23. /// <param name="user"></param>
  24. /// <returns></returns>
  25. public async Task<bool> SignIn(SystemUser user)
  26. {
  27. var claims = new[] {
  28. new Claim(ClaimTypes.Name, user.Account),
  29. new Claim("UserId", user.Id.ToString()),
  30. };
  31. identity = new ClaimsIdentity(claims, "user");
  32. NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
  33. return true;
  34. }
  35. /// <summary>
  36. /// 退出登录
  37. /// </summary>
  38. /// <returns></returns>
  39. public async Task<bool> SignOut()
  40. {
  41. // 用户认证成功,创建用户的ClaimsIdentity
  42. identity = new ClaimsIdentity();
  43. NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
  44. return true;
  45. }
  46. public override async Task<AuthenticationState> GetAuthenticationStateAsync()
  47. {
  48. //获取当前路由
  49. var currentRoute = _NavigationManager.ToBaseRelativePath(_NavigationManager.Uri);
  50. var user = new ClaimsPrincipal(identity);
  51. return new AuthenticationState(user);
  52. }
  53. }