asp.net mvc - Custom Authorization with Parameters Web API -
can show me how use parameter in customize authorizeattribute?
like this:
[authorize(role="admin,supervisor")] [authorize(user="me,you")] [authorize(action="abc,def")]
this code , dont have idea yet how add parameter here.
public class customauthorizeattribute : authorizeattribute { applicationdbcontext _context = new applicationdbcontext(); public override void onauthorization(httpactioncontext actioncontext) { if (authorizerequest(actioncontext)) { return; } handleunauthorizedrequest(actioncontext); } protected override void handleunauthorizedrequest(httpactioncontext actioncontext) { if (((system.web.httpcontext.current.user).identity).isauthenticated) { actioncontext.response = new httpresponsemessage() { statuscode = httpstatuscode.unauthorized, content = new stringcontent("you unauthorized access resource") }; } else { base.handleunauthorizedrequest(actioncontext); } } private bool authorizerequest(httpactioncontext actioncontext) { var action = actioncontext.actiondescriptor.actionname; var controller = actioncontext.controllercontext.controllerdescriptor.controllername; var currentuser = actioncontext.requestcontext.principal.identity.getuserid(); var user = _context.users.join(_context.useraccesses, x => x.roleid, y => y.roleid, (x, y) => new { id = x.id, firstname = x.firstname, lastname = x.lastname, roleid = x.roleid, controller = y.controller, action = y.action }).where(z => z.id == currentuser && z.controller == controller && z.action == action) .singleordefault(); if (user != null) return true; else return false; } }
as have extended default implementation of authorize
, need use [customauthorize(role="admin,supervisor")]
. set roles. can access roles
property directly in code contained in parent authorizeattribute
has been inherited.
public override void onauthorization(httpactioncontext actioncontext) { var roles = roles; if (authorizerequest(actioncontext)) { return; } handleunauthorizedrequest(actioncontext); }
Comments
Post a Comment