Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorization in ASP .NET Core Razor pages

I am unable to implement policy-based authorization in ASP .NET Core for an action on a razor page.

I read through this comprehensive document on authorization and used its examples as guidence.

Razor page action code:

[Authorize(Policy = "test")]
public async Task<IActionResult> OnGetCreateAsync(string id)

Code in service configuration:

_ = services.AddAuthorization(options => {
    options.AddPolicy("test", policy =>
        policy.RequireAssertion(context =>
            false));
});

I expect that if I call the action or endpoint service, e.g.

GET /Account?handler=Create

then the request will be denied with a 403 status response because the "test" policy states that everyone is unauthorized. However, in actual practice, the action is successfully called.

like image 391
shertu Avatar asked Aug 13 '19 12:08

shertu


People also ask

How do I Authorize a user in .NET Core?

Add the UseAuthentication middleware after UseRouting in the Configure method in the Startup file. This will enable us to authenticate using ASP.NET Core Identity. With all of this in place, the application Is all set to start using Identity.

What is authorization in ASP.NET Core?

Authentication is the process of determining a user's identity. Authorization is the process of determining whether a user has access to a resource. In ASP.NET Core, authentication is handled by the authentication service, IAuthenticationService, which is used by authentication middleware.

What is the use of razor pages in ASP.NET Core?

Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views. If you're looking for a tutorial that uses the Model-View-Controller approach, see Get started with ASP.NET Core MVC. This document provides an introduction to Razor Pages. It's not a step by step tutorial.


1 Answers

Razor Pages doesn't support [Authorize] at the handler level. i.e. You can only authorise a page as a whole, on the PageModel itself, as noted in the docs:

Policies can not be applied at the Razor Page handler level, they must be applied to the Page.

If authorising the page as a whole isn't a workable solution, you might need to move your OnGetCreateAsync handler into a controller/action pair, which can be attributed with [Authorize] accordingly.

There's also a related GitHub issue in the docs for this:

The [Authorize] filter attribute has been supported since 2.0 in Razor Pages, but note that it works at the page model class level

If you need a better workaround, see akbar's answer and Jim Yabro's answer.

like image 150
Kirk Larkin Avatar answered Oct 15 '22 23:10

Kirk Larkin