HotlineAuthenticator.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System.Net;
  2. using Fw.Utility.UnifyResponse;
  3. using RestSharp;
  4. using RestSharp.Authenticators;
  5. namespace Hotline.Api.Sdk;
  6. public class HotlineAuthenticator : AuthenticatorBase
  7. {
  8. private readonly string _tokenKey = "Authorization";
  9. private readonly string _baseUrl;
  10. private readonly string _apiKey;
  11. private readonly string _apiSecret;
  12. public HotlineAuthenticator(string baseUrl, string apiKey, string apiSecret) : base("")
  13. {
  14. _baseUrl = baseUrl;
  15. _apiKey = apiKey;
  16. _apiSecret = apiSecret;
  17. }
  18. protected override async ValueTask<Parameter> GetAuthenticationParameter(string accessToken)
  19. {
  20. if (string.IsNullOrEmpty(Token))
  21. Token = await GetTokenAsync(default);
  22. return new HeaderParameter(_tokenKey, Token);
  23. }
  24. public async Task<string> GetTokenAsync(CancellationToken cancellationToken)
  25. {
  26. var options = new RestClientOptions(_baseUrl);
  27. using var client = new RestClient(options);
  28. //var request = new RestRequest("api/v1/Identity/login/token")
  29. // .AddJsonBody(new TokenRequest { Username = _apiKey, Password = _apiSecret });
  30. try
  31. {
  32. var response = await client.PostJsonAsync<TokenRequest, ApiResponse<string>>("api/v1/Identity/login/token",
  33. new TokenRequest { Username = _apiKey, Password = _apiSecret }, cancellationToken);
  34. if (!response?.IsSuccess ?? false)
  35. throw new HttpRequestException(
  36. $"热线服务授权请求失败,HttpCode: {response.Code}, Error: {response.Error}");
  37. var token = response?.Result;
  38. if (string.IsNullOrEmpty(token))
  39. throw new HttpRequestException("热线服务授权失败");
  40. if (!token.StartsWith("Bearer"))
  41. token = "Bearer " + token;
  42. return token;
  43. //var response = await client.GetAsync(request, cancellationToken);
  44. //if (!response.IsSuccessful)
  45. // throw new HttpRequestException(
  46. // $"热线服务授权请求失败,HttpCode: {response.StatusCode}, Error: {response.ErrorMessage}");
  47. //var token = response.Headers?.FirstOrDefault(d => d.Name == _tokenKey);
  48. //if (token is null)
  49. // throw new HttpRequestException("热线服务授权失败");
  50. //if (token?.Value is null)
  51. // throw new HttpRequestException("热线token无效");
  52. //return token.Value.ToString();
  53. }
  54. catch (Exception e)
  55. {
  56. throw new HttpRequestException($"热线授权请求失败,Error: {e.Message}");
  57. }
  58. }
  59. public class TokenRequest
  60. {
  61. public string Username { get; set; }
  62. public string Password { get; set; }
  63. }
  64. }