0

How I can create CustomAuthenticationAttribute for an action in ASP.NET MVC 5 depend parameter, I mean if I sent to module 5, it means get data related teacher, and if I send 3 as parameter in module, return student. I want add two permissions (student and teacher) to allow user to access student or teacher or the both.

[CustomAuthentication(PermissionCode = "Student_View")]
public ActionResult Index(int module)
{
}

I have issue because the CustomAuthentication related page code (I will add two pieces of code) student_View and teacher_View

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Sam
  • 1
  • 1
    Attributes are applied at compile time, so they can’t behave differently based on a parameter – stuartd Feb 14 '21 at 17:07
  • So, Any solution to fix this issue , check permission depend parameter, May be add validation in Action ? – Sam Feb 14 '21 at 17:33

1 Answers1

0

I believe you can still access action parameters using the passed in AuthorizationContext depending on how your attribute is setup, doing something similar to this. I am inheriting from AuthorizeAttribute but this should work for other types of attributes as long as you can get access to the Request object.

You could also make the "module" property name dynamic by passing it into the attribute:

public class CustomAuthenticationAttribute : AuthorizeAttribute {
    public string ParamName { get; set; }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
        if (!string.IsNullOrEmpty(ParamName)) {
            if (filterContext.RequestContext.HttpContext.Request.QueryString[ParamName] != null) { // If using GET
                int module = int.Parse(filterContext.RequestContext.HttpContext.Request.QueryString[ParamName]);

                // Do something with module
            } else if (filterContext.RequestContext.HttpContext.Request.Form[ParamName] != null) { // If using POST (I have not tested Form before myself)
                int module = int.Parse(filterContext.RequestContext.HttpContext.Request.Form[ParamName]);

                // Do something with module
            }
        }
    }
}

And then you would use it like this:

[CustomAuthentication(ParamName = "module")]
public ActionResult Index(int module) { }
hvaughan3
  • 10,955
  • 5
  • 56
  • 76
  • Thanks for answer, But I want add permissionCode to allow user enter module , like if user add Student_View, it's mean enter student , and if add teacher_View , it's mean enter to teacher info, I want PermissionCode to define it to user to control access to pages (fake page) because its the same page – Sam Feb 15 '21 at 09:42
  • Are you understand what I mean , if you can help me – Sam Feb 16 '21 at 14:15
  • @Sam Not sure I follow. Please provide more code in your question. – hvaughan3 Feb 16 '21 at 22:18