MVC Custom Authorize Attribute to Test Request

I have a user interface with jQuery that calls an MVC call using an Ajax request.

I would like to check each request against userProfile (a custom class that contains an account number, identifier, etc.).

Can anyone suggest if you can create your own authorization attribute to verify that both requests and the user file are the same?

Then I would like to do something like below:

[AuthorizeUser] public ActionResult GetMyConsumption(string accountNumber) { ..... return View(); } 
+6
source share
1 answer

You can write your own Authorize attribute:

 public class AuthorizeUserAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { var isAuthorized = base.AuthorizeCore(httpContext); if (!isAuthorized) { // The user is not authorized => no need to continue return false; } // At this stage we know that the user is authorized => we can fetch // the username string username = httpContext.User.Identity.Name; // Now let fetch the account number from the request string account = httpContext.Request["accountNumber"]; // All that left is to verify if the current user is the owner // of the account return IsAccountOwner(username, account); } private bool IsAccountOwner(string username, string account) { // TODO: query the backend to perform the necessary verifications throw new NotImplementedException(); } } 
+17
source

Source: https://habr.com/ru/post/914189/


All Articles