blob: fb9f6d0a6e6a409dec51bd5645a180aceff3af3c (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
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>();
var requiresAuth = false;
// Add all method scopes.
foreach (var attribute in context.MethodInfo.GetCustomAttributes(true))
{
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);
if (controllerAttributes is not null)
{
foreach (var attribute in controllerAttributes)
{
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);
}
}
}
if (!requiresAuth)
{
return;
}
if (!operation.Responses.ContainsKey("401"))
{
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
}
if (!operation.Responses.ContainsKey("403"))
{
operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });
}
var scheme = new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = AuthenticationSchemes.CustomAuthentication
}
};
operation.Security = new List<OpenApiSecurityRequirement>
{
new OpenApiSecurityRequirement
{
[scheme] = requiredScopes
}
};
}
}
}
|