jellyfin/Jellyfin.Server/Middleware/CorsPolicyProvider.cs

50 lines
1.7 KiB
C#
Raw Normal View History

2020-09-05 15:10:05 +00:00
using System;
using System.Threading.Tasks;
using MediaBrowser.Controller.Configuration;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Http;
namespace Jellyfin.Server.Middleware
{
2020-09-05 15:10:05 +00:00
/// <summary>
/// Cors policy provider.
/// </summary>
public class CorsPolicyProvider : ICorsPolicyProvider
{
2020-09-05 15:10:05 +00:00
private readonly IServerConfigurationManager _serverConfigurationManager;
/// <summary>
/// Initializes a new instance of the <see cref="CorsPolicyProvider"/> class.
/// </summary>
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
public CorsPolicyProvider(IServerConfigurationManager serverConfigurationManager)
{
_serverConfigurationManager = serverConfigurationManager;
}
/// <inheritdoc />
public Task<CorsPolicy> GetPolicyAsync(HttpContext context, string policyName)
{
var corsHosts = _serverConfigurationManager.Configuration.CorsHosts;
var builder = new CorsPolicyBuilder()
.AllowAnyMethod()
.AllowAnyHeader();
// No hosts configured or only default configured.
if (corsHosts.Length == 0
|| (corsHosts.Length == 1
&& string.Equals(corsHosts[0], CorsConstants.AnyOrigin, StringComparison.Ordinal)))
{
builder.AllowAnyOrigin();
}
else
{
builder.WithOrigins(corsHosts)
.AllowCredentials();
}
return Task.FromResult(builder.Build());
}
}
}