AuthService.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Blazored.LocalStorage;
  2. using Microsoft.AspNetCore.Components.Authorization;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Net.Http.Json;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using wispro.sp.share.webViewObject;
  11. using wispro.sp.web.Auth;
  12. using System.Text.Json;
  13. namespace wispro.sp.web.Services
  14. {
  15. public class AuthService : IAuthService
  16. {
  17. private readonly ILocalStorageService localStorageService;
  18. private readonly IHttpService httpClient;
  19. private readonly AuthenticationStateProvider authenticationStateProvider;
  20. private IUserService UserService;
  21. public AuthService(ILocalStorageService localStorageService, IHttpService httpClient, AuthenticationStateProvider authenticationStateProvider, IUserService UserService)
  22. {
  23. this.localStorageService = localStorageService;
  24. this.httpClient = httpClient;
  25. this.authenticationStateProvider = authenticationStateProvider;
  26. this.UserService = UserService;
  27. }
  28. public async Task<bool> LoginAsync(loginDto userInfo)
  29. {
  30. bool result = false;
  31. var httpResponse = await httpClient.Post<userToken>($"account/Login", userInfo);
  32. if (httpResponse.StatusCode != System.Net.HttpStatusCode.NotFound)
  33. {
  34. userToken userToken = httpResponse;
  35. await localStorageService.SetItemAsync<userToken>("authToken", userToken);
  36. ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserAuthentication(userToken.Token);
  37. result = true;
  38. }
  39. //System.Threading.Thread.Sleep(1000);
  40. return result;
  41. }
  42. public async Task LogoutAsync()
  43. {
  44. await localStorageService.RemoveItemAsync("authToken");
  45. ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserLogOut();
  46. //httpClient.DefaultRequestHeaders.Authorization = null;
  47. }
  48. }
  49. }