AuthHelper.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Net;
  3. using System.Net.Http;
  4. using System.Net.Http.Headers;
  5. using System.Net.Http.Json;
  6. using System.Text.Json;
  7. using System.Threading.Tasks;
  8. using Jellyfin.Api.Models.StartupDtos;
  9. using Jellyfin.Api.Models.UserDtos;
  10. using Jellyfin.Extensions.Json;
  11. using Xunit;
  12. namespace Jellyfin.Server.Integration.Tests
  13. {
  14. public static class AuthHelper
  15. {
  16. public const string AuthHeaderName = "X-Emby-Authorization";
  17. public const string DummyAuthHeader = "MediaBrowser Client=\"Jellyfin.Server Integration Tests\", DeviceId=\"69420\", Device=\"Apple II\", Version=\"10.8.0\"";
  18. public static async Task<string> CompleteStartupAsync(HttpClient client)
  19. {
  20. var jsonOptions = JsonDefaults.Options;
  21. var userResponse = await client.GetByteArrayAsync("/Startup/User").ConfigureAwait(false);
  22. var user = JsonSerializer.Deserialize<StartupUserDto>(userResponse, jsonOptions);
  23. using var completeResponse = await client.PostAsync("/Startup/Complete", new ByteArrayContent(Array.Empty<byte>())).ConfigureAwait(false);
  24. Assert.Equal(HttpStatusCode.NoContent, completeResponse.StatusCode);
  25. using var content = JsonContent.Create(
  26. new AuthenticateUserByName()
  27. {
  28. Username = user!.Name,
  29. Pw = user.Password,
  30. },
  31. options: jsonOptions);
  32. content.Headers.Add("X-Emby-Authorization", DummyAuthHeader);
  33. using var authResponse = await client.PostAsync("/Users/AuthenticateByName", content).ConfigureAwait(false);
  34. var auth = await JsonSerializer.DeserializeAsync<AuthenticationResultDto>(
  35. await authResponse.Content.ReadAsStreamAsync().ConfigureAwait(false),
  36. jsonOptions).ConfigureAwait(false);
  37. return auth!.AccessToken;
  38. }
  39. public static void AddAuthHeader(this HttpHeaders headers, string accessToken)
  40. {
  41. headers.Add(AuthHeaderName, DummyAuthHeader + $", Token={accessToken}");
  42. }
  43. private class AuthenticationResultDto
  44. {
  45. public string AccessToken { get; set; } = string.Empty;
  46. public string ServerId { get; set; } = string.Empty;
  47. }
  48. }
  49. }