jellyfin/Jellyfin.Server/Filters/SecurityRequirementsOperationFilter.cs

92 lines
2.9 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using Jellyfin.Api.Constants;
using Microsoft.AspNetCore.Authorization;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace Jellyfin.Server.Filters
{
/// <summary>
/// Security requirement operation filter.
/// </summary>
public class SecurityRequirementsOperationFilter : IOperationFilter
{
/// <inheritdoc />
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var requiredScopes = new List<string>();
2023-02-09 06:56:53 -07:00
var requiresAuth = false;
// Add all method scopes.
foreach (var attribute in context.MethodInfo.GetCustomAttributes(true))
{
2023-02-09 06:56:53 -07:00
if (attribute is not AuthorizeAttribute authorizeAttribute)
{
continue;
}
requiresAuth = true;
if (authorizeAttribute.Policy is not null
&& !requiredScopes.Contains(authorizeAttribute.Policy, StringComparer.Ordinal))
{
requiredScopes.Add(authorizeAttribute.Policy);
}
}
// Add controller scopes if any.
var controllerAttributes = context.MethodInfo.DeclaringType?.GetCustomAttributes(true);
2022-12-05 07:01:13 -07:00
if (controllerAttributes is not null)
{
foreach (var attribute in controllerAttributes)
{
2023-02-09 06:56:53 -07:00
if (attribute is not AuthorizeAttribute authorizeAttribute)
{
continue;
}
requiresAuth = true;
if (authorizeAttribute.Policy is not null
&& !requiredScopes.Contains(authorizeAttribute.Policy, StringComparer.Ordinal))
{
requiredScopes.Add(authorizeAttribute.Policy);
}
}
}
2023-02-09 06:56:53 -07:00
if (!requiresAuth)
{
2023-02-09 06:56:53 -07:00
return;
}
2023-02-09 06:56:53 -07:00
if (!operation.Responses.ContainsKey("401"))
{
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
}
2023-02-09 06:56:53 -07:00
if (!operation.Responses.ContainsKey("403"))
{
operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });
}
var scheme = new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
2023-02-09 06:56:53 -07:00
Type = ReferenceType.SecurityScheme,
Id = AuthenticationSchemes.CustomAuthentication
}
};
2023-02-09 06:56:53 -07:00
operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
2023-02-09 06:56:53 -07:00
[scheme] = requiredScopes
}
};
}
}
2021-12-24 10:28:27 -07:00
}