JwtAuthenticationStateProvider.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. //沒有的話,回傳匿名使用者
  31. return anonymous;
  32. }
  33. //將token取出轉為claim
  34. var claims = JwtParser.ParseClaimsFromJwt(tokenInLocalStorage.Token);
  35. //在每次request的header中帶入bearer token
  36. httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", tokenInLocalStorage.Token);
  37. //回傳帶有user claim的AuthenticationState物件
  38. return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt")));
  39. }
  40. public void NotifyUserAuthentication(string token)
  41. {
  42. var claims = JwtParser.ParseClaimsFromJwt(token);
  43. var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt"));
  44. var authState = Task.FromResult(new AuthenticationState(authenticatedUser));
  45. NotifyAuthenticationStateChanged(authState);
  46. }
  47. public void NotifyUserLogOut()
  48. {
  49. var authState = Task.FromResult(anonymous);
  50. NotifyAuthenticationStateChanged(authState);
  51. }
  52. }
  53. }