Blazor & WASM in combination to get statistics from Spotify API for performing the song analysis. With separate microservices for auth, Spotify, user data tracking, and application, connected through gRPC with Polly.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

AuthService.cs 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //using IdentityProvider.Protos.AuthService;
  2. using Grpc.Net.Client;
  3. using GrpcShared;
  4. using GrpcShared.DTO.Auth;
  5. using GrpcShared.Interfaces;
  6. using Microsoft.Extensions.Options;
  7. using Microsoft.Net.Http.Headers;
  8. using Newtonsoft.Json;
  9. using System.Net.Http.Headers;
  10. using System.Text;
  11. using System.Text.Json;
  12. namespace IdentityProvider.Services
  13. {
  14. public class AuthService : IAuthService
  15. {
  16. private readonly ILogger<AuthService> _logger;
  17. private readonly CodeRequest _params;
  18. private readonly IHttpClientFactory _httpClientFactory;
  19. public AuthService(ILogger<AuthService> logger, IOptions<CodeRequest> options, IHttpClientFactory httpClientFactory)
  20. {
  21. _logger = logger;
  22. _params = options.Value;
  23. _httpClientFactory = httpClientFactory;
  24. }
  25. public async Task<TokenResponse> GetAccessToken(TokenRequest tokenRequest)
  26. {
  27. var http = _httpClientFactory.CreateClient();
  28. string url = "https://accounts.spotify.com/api/token";
  29. http.BaseAddress = new Uri(url);
  30. //get client id and secret from appsettings, convert to base64 and set as header
  31. var secrets = await GetAuthParams();
  32. byte[] contentType = Encoding.UTF8.GetBytes($"{secrets.ClientId}:{secrets.ClientSecret}");
  33. http.DefaultRequestHeaders.Add(HeaderNames.Authorization, "Basic " + Convert.ToBase64String(contentType));
  34. //ACCEPT HEADER
  35. http.DefaultRequestHeaders.Accept.Add(
  36. new MediaTypeWithQualityHeaderValue("application/json"));
  37. //BODY
  38. var requestBody = new Dictionary<string, string>();
  39. requestBody["grant_type"] = tokenRequest.grant_type;
  40. requestBody["code"] = tokenRequest.code!;
  41. requestBody["redirect_uri"] = secrets.RedirectURI!;
  42. var response = await http.PostAsync(url, new FormUrlEncodedContent(requestBody));
  43. var contents = JsonConvert.DeserializeObject<TokenResponse>(await response.Content.ReadAsStringAsync());
  44. return await Task.FromResult(new TokenResponse
  45. {
  46. AccessToken = contents!.AccessToken,
  47. RefreshToken = contents!.RefreshToken,
  48. ExpiresIn = contents!.ExpiresIn
  49. });
  50. }
  51. public async Task<CodeRequest> GetAuthParams()
  52. {
  53. var authParams = new CodeRequest
  54. {
  55. ClientId = _params.ClientId,
  56. RedirectURI = _params.RedirectURI,
  57. Scope = _params.Scope,
  58. ClientSecret = _params.ClientSecret
  59. };
  60. return await Task.FromResult(authParams);
  61. }
  62. }
  63. }