Razor Page Controllers (code behind) action authorize statements ignored
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.
- ID: b3668fea-5d71-a4fc-96d1-74b53906bf25
- Version Independent ID: 980a23e7-56e4-da94-a139-cab85135c5f7
- Content: Role-based authorization in ASP.NET Core
- Content Source: aspnetcore/security/authorization/roles.md
- Product: aspnet-core
- GitHub Login: @Rick-Anderson
- Microsoft Alias: riande
@blowdart please comment.
No idea, paging @rynowak
There is no support for filters on page handler methods. This is not a feature we have
Thanks @rynowak I'll update the doc to make that clear.
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.
Thank you @jwalker5006! I stumbled on this same issue just today and thought I was going crazy! ;-}
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(); } } });
Thanks for adding this code, it's very similar to what I came up with.