AuthService.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using Blazored.LocalStorage;
  2. using Microsoft.AspNetCore.Components.Authorization;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Net.Http.Json;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. using wispro.sp.share.webViewObject;
  12. using wispro.sp.web.Auth;
  13. namespace wispro.sp.web.Services
  14. {
  15. public class AuthService : IAuthService
  16. {
  17. private readonly ILocalStorageService localStorageService;
  18. private readonly HttpClient httpClient;
  19. private readonly AuthenticationStateProvider authenticationStateProvider;
  20. private IUserService UserService;
  21. public AuthService(ILocalStorageService localStorageService, HttpClient 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.PostAsJsonAsync<loginDto>($"http://localhost:39476/api/account/Login", userInfo);
  32. if (httpResponse.IsSuccessStatusCode)
  33. {
  34. userToken userToken = await httpResponse.Content.ReadFromJsonAsync<userToken>();
  35. await localStorageService.SetItemAsync<string>("authToken", userToken.Token);
  36. ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserAuthentication(userToken.Token);
  37. httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", userToken.Token);
  38. UserService.CurrentUser = new Models.CurrentUser() { Name = userToken.Name};
  39. result = true;
  40. }
  41. return result;
  42. }
  43. public async Task LogoutAsync()
  44. {
  45. await localStorageService.RemoveItemAsync("authToken");
  46. ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserLogOut();
  47. httpClient.DefaultRequestHeaders.Authorization = null;
  48. }
  49. }
  50. }