jellyfin/Jellyfin.Server.Implementations/Security/AuthorizationContext.cs

331 lines
12 KiB
C#
Raw Normal View History

2019-11-01 18:38:54 +01:00
#pragma warning disable CS1591
2014-11-15 03:31:03 +01:00
using System;
using System.Collections.Generic;
using System.Net;
2021-05-21 05:56:59 +02:00
using System.Threading.Tasks;
using EFCoreSecondLevelCacheInterceptor;
using MediaBrowser.Controller;
2018-09-12 19:26:21 +02:00
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using Microsoft.AspNetCore.Http;
2021-10-04 15:43:40 +02:00
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
2021-05-21 05:56:59 +02:00
namespace Jellyfin.Server.Implementations.Security
{
public class AuthorizationContext : IAuthorizationContext
{
2023-01-16 18:14:44 +01:00
private readonly IDbContextFactory<JellyfinDbContext> _jellyfinDbProvider;
2018-09-12 19:26:21 +02:00
private readonly IUserManager _userManager;
private readonly IServerApplicationHost _serverApplicationHost;
2014-11-15 03:31:03 +01:00
public AuthorizationContext(
2023-01-16 18:14:44 +01:00
IDbContextFactory<JellyfinDbContext> jellyfinDb,
IUserManager userManager,
IServerApplicationHost serverApplicationHost)
2014-11-15 03:31:03 +01:00
{
2021-06-18 23:06:38 +02:00
_jellyfinDbProvider = jellyfinDb;
2018-09-12 19:26:21 +02:00
_userManager = userManager;
_serverApplicationHost = serverApplicationHost;
2014-11-15 03:31:03 +01:00
}
2021-05-21 05:56:59 +02:00
public Task<AuthorizationInfo> GetAuthorizationInfo(HttpContext requestContext)
2014-11-15 03:31:03 +01:00
{
2022-12-05 15:01:13 +01:00
if (requestContext.Request.HttpContext.Items.TryGetValue("AuthorizationInfo", out var cached) && cached is not null)
2014-11-15 03:31:03 +01:00
{
return Task.FromResult((AuthorizationInfo)cached); // Cache should never contain null
2014-11-15 03:31:03 +01:00
}
return GetAuthorization(requestContext);
}
2021-05-21 05:56:59 +02:00
public async Task<AuthorizationInfo> GetAuthorizationInfo(HttpRequest requestContext)
{
var auth = GetAuthorizationDictionary(requestContext);
2021-05-21 05:56:59 +02:00
var authInfo = await GetAuthorizationInfoFromDictionary(auth, requestContext.Headers, requestContext.Query).ConfigureAwait(false);
return authInfo;
}
/// <summary>
/// Gets the authorization.
/// </summary>
/// <param name="httpReq">The HTTP req.</param>
/// <returns>Dictionary{System.StringSystem.String}.</returns>
2021-05-21 05:56:59 +02:00
private async Task<AuthorizationInfo> GetAuthorization(HttpContext httpReq)
{
var auth = GetAuthorizationDictionary(httpReq);
2021-05-21 05:56:59 +02:00
var authInfo = await GetAuthorizationInfoFromDictionary(auth, httpReq.Request.Headers, httpReq.Request.Query).ConfigureAwait(false);
2020-09-02 12:22:14 +02:00
httpReq.Request.HttpContext.Items["AuthorizationInfo"] = authInfo;
return authInfo;
}
2021-05-21 05:56:59 +02:00
private async Task<AuthorizationInfo> GetAuthorizationInfoFromDictionary(
IReadOnlyDictionary<string, string>? auth,
IHeaderDictionary headers,
IQueryCollection queryString)
{
string? deviceId = null;
2021-05-21 05:56:59 +02:00
string? deviceName = null;
string? client = null;
string? version = null;
string? token = null;
2022-12-05 15:01:13 +01:00
if (auth is not null)
{
auth.TryGetValue("DeviceId", out deviceId);
2021-05-21 05:56:59 +02:00
auth.TryGetValue("Device", out deviceName);
auth.TryGetValue("Client", out client);
auth.TryGetValue("Version", out version);
2017-01-13 22:05:12 +01:00
auth.TryGetValue("Token", out token);
}
2021-08-29 00:32:50 +02:00
#pragma warning disable CA1508 // string.IsNullOrEmpty(token) is always false.
if (string.IsNullOrEmpty(token))
{
token = headers["X-Emby-Token"];
2017-01-13 22:05:12 +01:00
}
2018-09-12 19:26:21 +02:00
if (string.IsNullOrEmpty(token))
2015-10-05 00:04:56 +02:00
{
token = headers["X-MediaBrowser-Token"];
2015-10-05 00:04:56 +02:00
}
2018-09-12 19:26:21 +02:00
if (string.IsNullOrEmpty(token))
{
token = queryString["ApiKey"];
}
// TODO deprecate this query parameter.
if (string.IsNullOrEmpty(token))
{
token = queryString["api_key"];
}
var authInfo = new AuthorizationInfo
{
Client = client,
2021-05-21 05:56:59 +02:00
Device = deviceName,
DeviceId = deviceId,
2014-07-02 20:34:08 +02:00
Version = version,
Token = token,
IsAuthenticated = false,
HasToken = false
};
2014-11-15 03:31:03 +01:00
2020-10-15 01:58:33 +02:00
if (string.IsNullOrWhiteSpace(token))
2014-11-15 03:31:03 +01:00
{
2020-10-15 01:58:33 +02:00
// Request doesn't contain a token.
return authInfo;
2020-10-15 01:58:33 +02:00
}
2021-05-21 05:56:59 +02:00
#pragma warning restore CA1508
2014-11-15 03:31:03 +01:00
authInfo.HasToken = true;
var dbContext = await _jellyfinDbProvider.CreateDbContextAsync().ConfigureAwait(false);
await using (dbContext.ConfigureAwait(false))
{
var device = await dbContext.Devices.FirstOrDefaultAsync(d => d.AccessToken == token).ConfigureAwait(false);
2022-12-05 15:01:13 +01:00
if (device is not null)
2020-10-15 01:58:33 +02:00
{
authInfo.IsAuthenticated = true;
var updateToken = false;
// TODO: Remove these checks for IsNullOrWhiteSpace
if (string.IsNullOrWhiteSpace(authInfo.Client))
{
authInfo.Client = device.AppName;
2018-09-12 19:26:21 +02:00
}
if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
2018-09-12 19:26:21 +02:00
{
authInfo.DeviceId = device.DeviceId;
2018-09-12 19:26:21 +02:00
}
// Temporary. TODO - allow clients to specify that the token has been shared with a casting device
var allowTokenInfoUpdate = !authInfo.Client.Contains("chromecast", StringComparison.OrdinalIgnoreCase);
if (string.IsNullOrWhiteSpace(authInfo.Device))
2021-11-11 06:43:43 +01:00
{
authInfo.Device = device.DeviceName;
2021-11-11 06:43:43 +01:00
}
else if (!string.Equals(authInfo.Device, device.DeviceName, StringComparison.OrdinalIgnoreCase))
2021-11-11 06:43:43 +01:00
{
if (allowTokenInfoUpdate)
{
updateToken = true;
device.DeviceName = authInfo.Device;
}
2021-11-11 06:43:43 +01:00
}
2021-11-12 22:23:58 +01:00
if (string.IsNullOrWhiteSpace(authInfo.Version))
2021-11-11 06:43:43 +01:00
{
authInfo.Version = device.AppVersion;
}
else if (!string.Equals(authInfo.Version, device.AppVersion, StringComparison.OrdinalIgnoreCase))
{
if (allowTokenInfoUpdate)
{
updateToken = true;
device.AppVersion = authInfo.Version;
}
}
if ((DateTime.UtcNow - device.DateLastActivity).TotalMinutes > 3)
{
device.DateLastActivity = DateTime.UtcNow;
updateToken = true;
2021-11-11 06:43:43 +01:00
}
authInfo.User = _userManager.GetUserById(device.UserId);
if (updateToken)
{
dbContext.Devices.Update(device);
await dbContext.SaveChangesAsync().ConfigureAwait(false);
}
}
else
{
var key = await dbContext.ApiKeys.FirstOrDefaultAsync(apiKey => apiKey.AccessToken == token).ConfigureAwait(false);
2022-12-05 15:01:13 +01:00
if (key is not null)
{
authInfo.IsAuthenticated = true;
authInfo.Client = key.Name;
authInfo.Token = key.AccessToken;
if (string.IsNullOrWhiteSpace(authInfo.DeviceId))
{
authInfo.DeviceId = _serverApplicationHost.SystemId;
}
if (string.IsNullOrWhiteSpace(authInfo.Device))
{
authInfo.Device = _serverApplicationHost.Name;
}
if (string.IsNullOrWhiteSpace(authInfo.Version))
{
authInfo.Version = _serverApplicationHost.ApplicationVersionString;
}
authInfo.IsApiKey = true;
}
2014-11-15 03:31:03 +01:00
}
return authInfo;
}
}
/// <summary>
/// Gets the auth.
/// </summary>
/// <param name="httpReq">The HTTP req.</param>
/// <returns>Dictionary{System.StringSystem.String}.</returns>
private static Dictionary<string, string>? GetAuthorizationDictionary(HttpContext httpReq)
{
2020-09-02 12:22:14 +02:00
var auth = httpReq.Request.Headers["X-Emby-Authorization"];
if (string.IsNullOrEmpty(auth))
{
2020-09-02 12:22:14 +02:00
auth = httpReq.Request.Headers[HeaderNames.Authorization];
}
return auth.Count > 0 ? GetAuthorization(auth[0]) : null;
}
/// <summary>
/// Gets the auth.
/// </summary>
/// <param name="httpReq">The HTTP req.</param>
/// <returns>Dictionary{System.StringSystem.String}.</returns>
private static Dictionary<string, string>? GetAuthorizationDictionary(HttpRequest httpReq)
{
2020-06-17 14:52:15 +02:00
var auth = httpReq.Headers["X-Emby-Authorization"];
2015-07-03 13:51:45 +02:00
2018-09-12 19:26:21 +02:00
if (string.IsNullOrEmpty(auth))
2015-07-03 13:51:45 +02:00
{
auth = httpReq.Headers[HeaderNames.Authorization];
2015-07-03 13:51:45 +02:00
}
return auth.Count > 0 ? GetAuthorization(auth[0]) : null;
}
/// <summary>
/// Gets the authorization.
/// </summary>
/// <param name="authorizationHeader">The authorization header.</param>
/// <returns>Dictionary{System.StringSystem.String}.</returns>
private static Dictionary<string, string>? GetAuthorization(ReadOnlySpan<char> authorizationHeader)
{
2021-05-16 14:49:11 +02:00
var firstSpace = authorizationHeader.IndexOf(' ');
2021-05-16 14:49:11 +02:00
// There should be at least two parts
if (firstSpace == -1)
{
return null;
}
2021-05-16 14:49:11 +02:00
var name = authorizationHeader[..firstSpace];
2017-01-13 22:05:12 +01:00
2021-05-16 14:49:11 +02:00
if (!name.Equals("MediaBrowser", StringComparison.OrdinalIgnoreCase)
&& !name.Equals("Emby", StringComparison.OrdinalIgnoreCase))
{
return null;
}
2021-02-26 15:30:00 +01:00
// Remove up until the first space
authorizationHeader = authorizationHeader[(firstSpace + 1)..];
return GetParts(authorizationHeader);
2020-12-14 14:05:53 +01:00
}
2020-12-15 21:06:47 +01:00
/// <summary>
/// Get the authorization header components.
/// </summary>
/// <param name="authorizationHeader">The authorization header.</param>
/// <returns>Dictionary{System.StringSystem.String}.</returns>
public static Dictionary<string, string> GetParts(ReadOnlySpan<char> authorizationHeader)
{
2021-02-26 15:30:00 +01:00
var result = new Dictionary<string, string>();
var escaped = false;
int start = 0;
2021-02-26 15:30:00 +01:00
string key = string.Empty;
2021-06-03 17:10:19 +02:00
int i;
for (i = 0; i < authorizationHeader.Length; i++)
{
var token = authorizationHeader[i];
2021-06-03 17:10:19 +02:00
if (token == '"' || token == ',')
{
// Applying a XOR logic to evaluate whether it is opening or closing a value
escaped = (!escaped) == (token == '"');
if (token == ',' && !escaped)
{
// Meeting a comma after a closing escape char means the value is complete
if (start < i)
{
result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
2021-02-26 15:30:00 +01:00
key = string.Empty;
}
start = i + 1;
}
}
2021-02-26 15:30:00 +01:00
else if (!escaped && token == '=')
{
key = authorizationHeader[start.. i].Trim().ToString();
2021-02-26 15:30:00 +01:00
start = i + 1;
}
}
// Add last value
if (start < i)
{
result[key] = WebUtility.UrlDecode(authorizationHeader[start..i].Trim('"').ToString());
}
2021-02-26 15:30:00 +01:00
return result;
}
}
}