Vladislav Moiseev
Vladislav Moiseev

Reputation: 23

Is it safe to use .RequireRole() without .RequireAuthenticatedUser() in ASP.NET Core authorization policies?

There are some policies defines in Startup.cs like:

services.AddAuthorization(options =>
{
    options.AddPolicy("UsersEdit", policy => policy
        .RequireAuthenticatedUser()
        .RequireRole("Admin"));
});

Is it safe to rewrote this code to:

services.AddAuthorization(options =>
{
    options.AddPolicy("UsersEdit", policy => policy.RequireRole("Admin"));
});

I guess that unauthorized user can't have any roles.

Upvotes: 2

Views: 2178

Answers (1)

juunas
juunas

Reputation: 58898

If we check the source code for the authorization requirement that gets added by RequireAuthenticatedUser at https://github.com/aspnet/AspNetCore/blob/c376e833e46497fbec4bd7b39632f8c8e13360b2/src/Security/Authorization/Core/src/DenyAnonymousAuthorizationRequirement.cs:

var user = context.User;
var userIsAnonymous =
    user?.Identity == null ||
    !user.Identities.Any(i => i.IsAuthenticated);
    if (!userIsAnonymous)
    {
        context.Succeed(requirement);
    }

It adds a check that user must have an identity, and that one of them must say the user is authenticated.

IsAuthenticated says the following in the docs:

true if the AuthenticationType property is not null or an empty string.

So in theory a user could have a role by having an identity that has no authentication type. But in practice, that should not happen. Any reasonable authentication handler would not leave AuthenticationType empty, since then IsAuthenticated would return false.

Upvotes: 1

Related Questions