AuthService.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. public async Task<List<string>> GetRoles(string resourceId)
  49. {
  50. var httpResponse = await httpClient.Get<List<string>>($"account/GetRoles?ResourceId={resourceId}");
  51. return httpResponse;
  52. }
  53. }
  54. }