Fix broken CookieAuthenticationRedirect caused by PR #14036 for non-api requests (#14399)

* Fix broken CookieAuthenticationRedirect caused by PR #14036 when not in an API controller

* Added Integration Tests for the MemberAuthorizationFilter

* Fix merge conflict

---------

Co-authored-by: Elitsa <elm@umbraco.dk>
(cherry picked from commit 1d239a30ca)
This commit is contained in:
Maarten
2023-07-04 09:37:13 +02:00
committed by Sebastiaan Janssen
parent 30ec9d9bc7
commit 3f196a9de4
3 changed files with 141 additions and 4 deletions

View File

@@ -60,14 +60,14 @@ public class UmbracoMemberAuthorizeFilter : IAsyncAuthorizationFilter
{
context.HttpContext.SetReasonPhrase(
"Resource restricted: the member is not of a permitted type or group.");
context.HttpContext.Response.StatusCode = 403;
context.Result = new ForbidResult();
}
}
else
{
context.HttpContext.SetReasonPhrase(
"Resource restricted: the member is not logged in.");
context.Result = new UnauthorizedResult();
context.HttpContext.Response.StatusCode = 401;
context.Result = new ForbidResult();
}
}

View File

@@ -1,10 +1,12 @@
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Umbraco.Cms.Core.Routing;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Web.Common.Controllers;
using Umbraco.Extensions;
namespace Umbraco.Cms.Web.Common.Security;
@@ -58,7 +60,16 @@ public sealed class ConfigureMemberCookieOptions : IConfigureNamedOptions<Cookie
},
OnRedirectToAccessDenied = ctx =>
{
ctx.Response.StatusCode = StatusCodes.Status403Forbidden;
// When the controller is an UmbracoAPIController, we want to return a StatusCode instead of a redirect.
// All other cases should use the default Redirect of the CookieAuthenticationEvent.
var controllerDescriptor = ctx.HttpContext.GetEndpoint()?.Metadata
.OfType<ControllerActionDescriptor>()
.FirstOrDefault();
if (!controllerDescriptor?.ControllerTypeInfo.IsSubclassOf(typeof(UmbracoApiController)) ?? false)
{
new CookieAuthenticationEvents().OnRedirectToAccessDenied(ctx);
}
return Task.CompletedTask;
},