Skip to content

Commit e6413aa

Browse files
committed
Fix: AllowAnonymous attribute on Action is ignored when UmbracoMemberAuthorize is set on Controller
Ref: #11125
1 parent 36582f2 commit e6413aa

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/Umbraco.Web.Common/Filters/UmbracoMemberAuthorizeFilter.cs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
using System.Collections.Generic;
22
using System.Threading.Tasks;
3+
4+
using Microsoft.AspNetCore.Authorization;
5+
using Microsoft.AspNetCore.Http;
36
using Microsoft.AspNetCore.Mvc;
7+
using Microsoft.AspNetCore.Mvc.Authorization;
48
using Microsoft.AspNetCore.Mvc.Filters;
59
using Microsoft.Extensions.DependencyInjection;
610
using Umbraco.Cms.Core.Security;
@@ -42,6 +46,12 @@ public UmbracoMemberAuthorizeFilter(string allowType, string allowGroup, string
4246

4347
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
4448
{
49+
// Allow Anonymous skips all authorization
50+
if (HasAllowAnonymous(context))
51+
{
52+
return;
53+
}
54+
4555
IMemberManager memberManager = context.HttpContext.RequestServices.GetRequiredService<IMemberManager>();
4656

4757
if (!await IsAuthorizedAsync(memberManager))
@@ -51,6 +61,32 @@ public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
5161
}
5262
}
5363

64+
/// <summary>
65+
/// Copied from https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Core/src/Authorization/AuthorizeFilter.cs
66+
/// </summary>
67+
private bool HasAllowAnonymous(AuthorizationFilterContext context)
68+
{
69+
var filters = context.Filters;
70+
for (var i = 0; i < filters.Count; i++)
71+
{
72+
if (filters[i] is IAllowAnonymousFilter)
73+
{
74+
return true;
75+
}
76+
}
77+
78+
// When doing endpoint routing, MVC does not add AllowAnonymousFilters for AllowAnonymousAttributes that
79+
// were discovered on controllers and actions. To maintain compat with 2.x,
80+
// we'll check for the presence of IAllowAnonymous in endpoint metadata.
81+
var endpoint = context.HttpContext.GetEndpoint();
82+
if (endpoint?.Metadata?.GetMetadata<IAllowAnonymous>() != null)
83+
{
84+
return true;
85+
}
86+
87+
return false;
88+
}
89+
5490
private async Task<bool> IsAuthorizedAsync(IMemberManager memberManager)
5591
{
5692
if (AllowMembers.IsNullOrWhiteSpace())

0 commit comments

Comments
 (0)