JwtAuthenticationStateProvider.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using Microsoft.AspNetCore.Components.Authorization;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Blazored.LocalStorage;
  7. using System.Security.Claims;
  8. using System.Net.Http;
  9. using wispro.sp.web.Utils;
  10. using wispro.sp.share.webViewObject;
  11. namespace wispro.sp.web.Auth
  12. {
  13. public class JwtAuthenticationStateProvider : AuthenticationStateProvider
  14. {
  15. private readonly ILocalStorageService localStorageService;
  16. private readonly HttpClient httpClient;
  17. private AuthenticationState anonymous;
  18. public JwtAuthenticationStateProvider(ILocalStorageService localStorageService, HttpClient httpClient)
  19. {
  20. anonymous = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
  21. this.localStorageService = localStorageService;
  22. this.httpClient = httpClient;
  23. }
  24. public override async Task<AuthenticationState> GetAuthenticationStateAsync()
  25. {
  26. //確認localstorage裡面是否有token
  27. var tokenInLocalStorage = await localStorageService.GetItemAsync<userToken>("authToken");
  28. if (tokenInLocalStorage == null)
  29. {
  30. Console.WriteLine($"Token:匿名!");
  31. //沒有的話,回傳匿名使用者
  32. return anonymous;
  33. }
  34. //將token取出轉為claim
  35. var claims = JwtParser.ParseClaimsFromJwt(tokenInLocalStorage.Token);
  36. Console.WriteLine($"Token:{tokenInLocalStorage.Token}");
  37. //在每次request的header中帶入bearer token
  38. httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", tokenInLocalStorage.Token);
  39. //回傳帶有user claim的AuthenticationState物件
  40. return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt")));
  41. }
  42. public void NotifyUserAuthentication(string token)
  43. {
  44. var claims = JwtParser.ParseClaimsFromJwt(token);
  45. var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt"));
  46. var authState = Task.FromResult(new AuthenticationState(authenticatedUser));
  47. NotifyAuthenticationStateChanged(authState);
  48. }
  49. public void NotifyUserLogOut()
  50. {
  51. var authState = Task.FromResult(anonymous);
  52. NotifyAuthenticationStateChanged(authState);
  53. }
  54. }
  55. }