-
Notifications
You must be signed in to change notification settings - Fork 0
/
AuthorizeCheckOperationFilter.cs
82 lines (76 loc) · 2.72 KB
/
AuthorizeCheckOperationFilter.cs
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
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace ODataTest
{
/// <summary>
/// Swagger UI authorization filter.
/// </summary>
public class AuthorizeCheckOperationFilter : IOperationFilter
{
/// <summary>
/// Swagger UI authorization filter.
/// </summary>
/// <param name="options">Api Security Options.</param>
public AuthorizeCheckOperationFilter(IOptions<ApiSecurityOptions> options)
{
_options = options;
}
/// <summary>
/// Apply filter.
/// </summary>
/// <param name="operation">Open Api operation.</param>
/// <param name="context">Operation context.</param>
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var hasAuthorize = context.MethodInfo.DeclaringType != null
&& !context.MethodInfo
.GetCustomAttributes(true)
.OfType<AllowAnonymousAttribute>()
.Any()
&& (context.MethodInfo.DeclaringType
.GetCustomAttributes(true)
.OfType<AuthorizeAttribute>()
.Any()
|| context.MethodInfo
.GetCustomAttributes(true)
.OfType<AuthorizeAttribute>()
.Any());
if (hasAuthorize)
{
operation.Responses.Add("401", new OpenApiResponse { Description = "Unauthorized" });
operation.Responses.Add("403", new OpenApiResponse { Description = "Forbidden" });
operation.Security.Add(ConfigureSecurityRequirement(_options.Value));
}
}
private static OpenApiSecurityRequirement ConfigureSecurityRequirement(ApiSecurityOptions options)
{
if (_requirement == null)
{
_requirement = new OpenApiSecurityRequirement
{
{
_scheme,
new[]
{
options.Audience
}
}
};
}
return _requirement;
}
private static OpenApiSecurityRequirement _requirement;
private readonly static OpenApiSecurityScheme _scheme = new()
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = ApiInfo.SchemeOauth2
}
};
private readonly IOptions<ApiSecurityOptions> _options;
}
}