JwtAuthenticationStateProvider.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. namespace wispro.sp.web.Auth
  11. {
  12. public class JwtAuthenticationStateProvider : AuthenticationStateProvider
  13. {
  14. private readonly ILocalStorageService localStorageService;
  15. private readonly HttpClient httpClient;
  16. private AuthenticationState anonymous;
  17. public JwtAuthenticationStateProvider(ILocalStorageService localStorageService, HttpClient httpClient)
  18. {
  19. anonymous = new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));
  20. this.localStorageService = localStorageService;
  21. this.httpClient = httpClient;
  22. }
  23. public override async Task<AuthenticationState> GetAuthenticationStateAsync()
  24. {
  25. //確認localstorage裡面是否有token
  26. string tokenInLocalStorage = await localStorageService.GetItemAsStringAsync("authToken");
  27. if (string.IsNullOrEmpty(tokenInLocalStorage))
  28. {
  29. //沒有的話,回傳匿名使用者
  30. return null;
  31. }
  32. //將token取出轉為claim
  33. var claims = JwtParser.ParseClaimsFromJwt(tokenInLocalStorage);
  34. //在每次request的header中帶入bearer token
  35. httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", tokenInLocalStorage);
  36. //回傳帶有user claim的AuthenticationState物件
  37. return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt")));
  38. }
  39. public void NotifyUserAuthentication(string token)
  40. {
  41. var claims = JwtParser.ParseClaimsFromJwt(token);
  42. var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt"));
  43. var authState = Task.FromResult(new AuthenticationState(authenticatedUser));
  44. NotifyAuthenticationStateChanged(authState);
  45. }
  46. public void NotifyUserLogOut()
  47. {
  48. var authState = Task.FromResult(anonymous);
  49. NotifyAuthenticationStateChanged(authState);
  50. }
  51. }
  52. }