Require authentication regardless of permissions settings

Ted
Ted
Vote:
 

What would you suggest being the best way to lock down an environment (e.g. preproduction in Content Cloud), regardless of permissions settings, through code?

The goal is to require authentication for all users, regardless of any permissions set for the Everyone role.

For IIS, we commonly did this through web.config

<deny users="?"/>

We'd like to do the equivalent through code in a server-agnostic way.

Logically I'd like to add an authentication requirement to all registered authorization policies.

I could obviously use some middleware and short-circuit with a 401 Unauthorized, but I want the authentication middleware to handle the request as if authentication is required and redirect the user to whatever authentication method is being used.

Simply changing the response status to 401 without short-circuiting does indeed affect the response header, but page content is still served - albeit with a 401 status code. 🙈

#275320
Mar 02, 2022 16:53
Vote:
 

I think something like this should work.  https://scottsauber.com/2020/01/20/globally-require-authenticated-users-by-default-using-fallback-policies-in-asp-net-core/

#275572
Mar 03, 2022 3:22
Ted
Vote:
 

That's one of the options I tried, but I was unable to get it to stick.

As he mentions in the post: "default to every single Controller and Razor Page ONLY WHEN no other attribute is specified"

I can get it to work for my own vanilla controllers for example, but it has no effect on CMS content.

#275580
Mar 03, 2022 7:10
Vote:
 

What about something like this:

public class RequireAuthenticatedHandler : IAuthorizationHandler
{
    public Task HandleAsync(AuthorizationHandlerContext context)
    {
        if (!(context.User.Identity?.IsAuthenticated ?? false))
        {
            context.Fail();
        }

        return Task.CompletedTask;
    }
}

And in startup:

services.TryAddEnumerable(ServiceDescriptor.Transient<IAuthorizationHandler, RequireAuthenticatedHandler>());
#275582
Mar 03, 2022 7:56
Ted
Vote:
 

Ah, good idea, Mattias! That did the trick! 👍 Thanks!

#275585
Mar 03, 2022 8:50
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.