AspNetCore.Docs icon indicating copy to clipboard operation
AspNetCore.Docs copied to clipboard

Razor Page Controllers (code behind) action authorize statements ignored

Open jwalker5006 opened this issue 8 years ago • 8 comments

I have a razor page with Authorize declared above class, then some actions which a role authorize declared. but the action authorize statements are ignored. [Authorize] public class DetailModel : PageModel {//Detail Model stuff}

[Authorize(Roles = "Admin,PartnerAdmin")] public JsonResult OnPostAddTech() { //Do Stuff if authorized }

The Note saying "Role-based authorization checks are declarative—the developer embeds them within their code, against a controller or an action within a controller," I assumed also included razor page code behind controllers, but does not see to be working 100% the same was as a controller.


Document Details

⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

jwalker5006 avatar Jul 11 '18 19:07 jwalker5006

@blowdart please comment.

Rick-Anderson avatar Jul 11 '18 19:07 Rick-Anderson

No idea, paging @rynowak

blowdart avatar Jul 11 '18 19:07 blowdart

There is no support for filters on page handler methods. This is not a feature we have

rynowak avatar Jul 11 '18 22:07 rynowak

Thanks @rynowak I'll update the doc to make that clear.

Rick-Anderson avatar Jul 11 '18 23:07 Rick-Anderson

I was able to work around the issue I had but using the user.isinrole within the code to handle role based actions. Hoping of someone else reads this and needs to control what code runs within a razor controller page, they can use the isinRole method.

jwalker5006 avatar Jul 12 '18 00:07 jwalker5006

Thank you @jwalker5006! I stumbled on this same issue just today and thought I was going crazy! ;-}

samconn avatar Jul 15 '18 05:07 samconn

My Work Around for razor pages code behind is - for isInrole example only. this is not showing you how to properly update data. public JsonResult OnPostAddStuff(int theId, string newValue) { if (!User.IsInRole("Admin")) { return new JsonResult("User Denied"); Console.WriteLine("User should not be doing this"); } var stuff = new TblStuff(); stuff.TheId = theId; stuff.SomeData = newValue; _Context.TblStuff.Add(stuff); _Context.SaveChanges(); return new JsonResult("OK"); }

In the javascript/ajax you can test for success, failure, and on success, test for OK or not, and return permission reasons to user if not authorized.

$.ajax({ url: '?handler=AddStuff', type: 'POST', data: { __RequestVerificationToken: token, theId: selectedId, newValue: theValue, }, success: function (json) { if (json != "OK") { alert(json); } else { displayStuff(); } } });

jwalker5006 avatar Jul 17 '18 15:07 jwalker5006

Thanks for adding this code, it's very similar to what I came up with.

samconn avatar Jul 19 '18 05:07 samconn