From bda7ffaae83ab4942f5dcb2aab628d91180f375f Mon Sep 17 00:00:00 2001 From: iven <99438726+ivenos@users.noreply.github.com> Date: Wed, 7 Oct 2026 18:47:59 +0200 Subject: Return the created API key from POST /Auth/Keys (#17155) * Return the created API key from POST /Auth/Keys * Keep the other API key fields in the DTO --- Jellyfin.Api/Controllers/ApiKeyController.cs | 37 +++++++--- .../Models/ApiKeyDtos/AuthenticationInfoDto.cs | 69 +++++++++++++++++++ .../Security/AuthenticationManager.cs | 15 +++- .../Security/IAuthenticationManager.cs | 4 +- .../Security/AuthenticationManagerTests.cs | 80 ++++++++++++++++++++++ 5 files changed, 192 insertions(+), 13 deletions(-) create mode 100644 Jellyfin.Api/Models/ApiKeyDtos/AuthenticationInfoDto.cs create mode 100644 tests/Jellyfin.Server.Implementations.Tests/Security/AuthenticationManagerTests.cs diff --git a/Jellyfin.Api/Controllers/ApiKeyController.cs b/Jellyfin.Api/Controllers/ApiKeyController.cs index 161479e4ca..2fa7b649af 100644 --- a/Jellyfin.Api/Controllers/ApiKeyController.cs +++ b/Jellyfin.Api/Controllers/ApiKeyController.cs @@ -1,6 +1,8 @@ using System.ComponentModel.DataAnnotations; +using System.Linq; using System.Threading.Tasks; using Jellyfin.Api.Constants; +using Jellyfin.Api.Models.ApiKeyDtos; using MediaBrowser.Common.Api; using MediaBrowser.Controller.Security; using MediaBrowser.Model.Querying; @@ -32,31 +34,31 @@ public class ApiKeyController : BaseJellyfinApiController /// Get all keys. /// /// Api keys retrieved. - /// A with all keys. + /// A with all keys. [HttpGet("Keys")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status200OK)] - public async Task>> GetKeys() + public async Task>> GetKeys() { var keys = await _authenticationManager.GetApiKeys().ConfigureAwait(false); - return new QueryResult(keys); + return new QueryResult(keys.Select(ToDto).ToList()); } /// /// Create a new api key. /// /// Name of the app using the authentication key. - /// Api key created. - /// A . + /// Api key created. + /// The created api key. [HttpPost("Keys")] [Authorize(Policy = Policies.RequiresElevation)] - [ProducesResponseType(StatusCodes.Status204NoContent)] - public async Task CreateKey([FromQuery, Required] string app) + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task> CreateKey([FromQuery, Required] string app) { - await _authenticationManager.CreateApiKey(app).ConfigureAwait(false); + var key = await _authenticationManager.CreateApiKey(app).ConfigureAwait(false); - return NoContent(); + return ToDto(key); } /// @@ -74,4 +76,21 @@ public class ApiKeyController : BaseJellyfinApiController return NoContent(); } + + private static AuthenticationInfoDto ToDto(AuthenticationInfo info) + => new() + { + Id = info.Id, + AccessToken = info.AccessToken, + DeviceId = info.DeviceId, + AppName = info.AppName, + AppVersion = info.AppVersion, + DeviceName = info.DeviceName, + UserId = info.UserId, + IsActive = info.IsActive, + DateCreated = info.DateCreated, + DateRevoked = info.DateRevoked, + DateLastActivity = info.DateLastActivity, + UserName = info.UserName + }; } diff --git a/Jellyfin.Api/Models/ApiKeyDtos/AuthenticationInfoDto.cs b/Jellyfin.Api/Models/ApiKeyDtos/AuthenticationInfoDto.cs new file mode 100644 index 0000000000..945fded532 --- /dev/null +++ b/Jellyfin.Api/Models/ApiKeyDtos/AuthenticationInfoDto.cs @@ -0,0 +1,69 @@ +using System; + +namespace Jellyfin.Api.Models.ApiKeyDtos; + +/// +/// An API key. +/// +public class AuthenticationInfoDto +{ + /// + /// Gets or sets the identifier. + /// + public long Id { get; set; } + + /// + /// Gets or sets the access token. + /// + public string? AccessToken { get; set; } + + /// + /// Gets or sets the device identifier. + /// + public string? DeviceId { get; set; } + + /// + /// Gets or sets the name of the app using the key. + /// + public string? AppName { get; set; } + + /// + /// Gets or sets the application version. + /// + public string? AppVersion { get; set; } + + /// + /// Gets or sets the name of the device. + /// + public string? DeviceName { get; set; } + + /// + /// Gets or sets the user identifier. + /// + public Guid UserId { get; set; } + + /// + /// Gets or sets a value indicating whether this instance is active. + /// + public bool IsActive { get; set; } + + /// + /// Gets or sets the date the key was created. + /// + public DateTime DateCreated { get; set; } + + /// + /// Gets or sets the date the key was revoked. + /// + public DateTime? DateRevoked { get; set; } + + /// + /// Gets or sets the date of the last activity. + /// + public DateTime DateLastActivity { get; set; } + + /// + /// Gets or sets the user name. + /// + public string? UserName { get; set; } +} diff --git a/Jellyfin.Server.Implementations/Security/AuthenticationManager.cs b/Jellyfin.Server.Implementations/Security/AuthenticationManager.cs index cf0293463f..2bc7b9f915 100644 --- a/Jellyfin.Server.Implementations/Security/AuthenticationManager.cs +++ b/Jellyfin.Server.Implementations/Security/AuthenticationManager.cs @@ -23,14 +23,25 @@ namespace Jellyfin.Server.Implementations.Security } /// - public async Task CreateApiKey(string name) + public async Task CreateApiKey(string name) { var dbContext = await _dbProvider.CreateDbContextAsync().ConfigureAwait(false); await using (dbContext.ConfigureAwait(false)) { - dbContext.ApiKeys.Add(new ApiKey(name)); + var apiKey = new ApiKey(name); + dbContext.ApiKeys.Add(apiKey); await dbContext.SaveChangesAsync().ConfigureAwait(false); + + return new AuthenticationInfo + { + AppName = apiKey.Name, + AccessToken = apiKey.AccessToken, + DateCreated = apiKey.DateCreated, + DeviceId = string.Empty, + DeviceName = string.Empty, + AppVersion = string.Empty + }; } } diff --git a/MediaBrowser.Controller/Security/IAuthenticationManager.cs b/MediaBrowser.Controller/Security/IAuthenticationManager.cs index 79b2a2444e..aebb229e79 100644 --- a/MediaBrowser.Controller/Security/IAuthenticationManager.cs +++ b/MediaBrowser.Controller/Security/IAuthenticationManager.cs @@ -12,8 +12,8 @@ namespace MediaBrowser.Controller.Security /// Creates an API key. /// /// The name of the key. - /// A task representing the creation of the key. - Task CreateApiKey(string name); + /// A task representing the creation of the key, containing the created key. + Task CreateApiKey(string name); /// /// Gets the API keys. diff --git a/tests/Jellyfin.Server.Implementations.Tests/Security/AuthenticationManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Security/AuthenticationManagerTests.cs new file mode 100644 index 0000000000..e46b88c67e --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Security/AuthenticationManagerTests.cs @@ -0,0 +1,80 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Jellyfin.Database.Implementations; +using Jellyfin.Database.Implementations.Locking; +using Jellyfin.Database.Providers.Sqlite; +using Jellyfin.Server.Implementations.Security; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.Security +{ + public sealed class AuthenticationManagerTests : IDisposable + { + private readonly SqliteConnection _connection; + private readonly DbContextOptions _dbOptions; + private readonly AuthenticationManager _authenticationManager; + + public AuthenticationManagerTests() + { + _connection = new SqliteConnection("Data Source=:memory:"); + _connection.Open(); + + _dbOptions = new DbContextOptionsBuilder() + .UseSqlite(_connection) + .Options; + + // Create the schema + using var ctx = CreateDbContext(); + ctx.Database.EnsureCreated(); + + var factory = new Mock>(); + factory.Setup(f => f.CreateDbContext()).Returns(CreateDbContext); + factory.Setup(f => f.CreateDbContextAsync(It.IsAny())) + .ReturnsAsync(CreateDbContext); + + _authenticationManager = new AuthenticationManager(factory.Object); + } + + public void Dispose() + { + _connection.Dispose(); + } + + private JellyfinDbContext CreateDbContext() + { + return new JellyfinDbContext( + _dbOptions, + NullLogger.Instance, + new SqliteDatabaseProvider(null!, NullLogger.Instance), + new NoLockBehavior(NullLogger.Instance)); + } + + [Fact] + public async Task CreateApiKey_ReturnsInfoMatchingStoredKey() + { + var created = await _authenticationManager.CreateApiKey("test-app"); + + Assert.Equal("test-app", created.AppName); + Assert.False(string.IsNullOrEmpty(created.AccessToken)); + + var keys = await _authenticationManager.GetApiKeys(); + var stored = Assert.Single(keys); + Assert.Equal(created.AppName, stored.AppName); + Assert.Equal(created.AccessToken, stored.AccessToken); + } + + [Fact] + public async Task CreateApiKey_WithMultipleKeys_ReturnsDistinctTokens() + { + var first = await _authenticationManager.CreateApiKey("app1"); + var second = await _authenticationManager.CreateApiKey("app2"); + + Assert.NotEqual(first.AccessToken, second.AccessToken); + } + } +} -- cgit v1.2.3