MVC Blog: Claims and Policy-based Authorization


Garry West
09/15/2024

Right now, a visitor to my Index and Details views sees buttons for creating, editing and deleting posts.

I'd like to restrict that to Admin users, and make sure no one else can make those requests.

Since I want to only allow general users access to a few areas of the application, I create a new policy authorization in Program.cs:

I then apply an Authorize attribute to \Controllers\BlogPostController.cs:

And a couple of AllowAnonymous attributes where I want the general public to be able to see things, namely Index and Details:

If I try and access Edit, Delete or Create, I get a friendly reminder that I am missing that claim:

I'd also like to hide the create, edit and delete buttons if the user is not an admin. In \Views\BlogPost\Index.cshtml:

And in \Views\BlogPost\Details.cshtml:

So now a non-admin user will not even see the buttons:

Index:

Details:

blog , identity , mvc