Monday, 15 July 2013

ASP.NET MVC 4 Authorization for same user or else Admin -



ASP.NET MVC 4 Authorization for same user or else Admin -

hi want set authorization filter on action method in controller can access same user or else admin.

suppose there user alex registers website , want edit profile. should allowed edit profile not others or admin have rights edit everyone's profile.

i can add together role admin in authorize attribute how tackle self user thing. kindly help

[authorize(roles="admin")]

this illustration of authorization filter check if user name (it can guid or other method) matches parameter passed route , checks user role on admin

public class customauthorizeattribute : authorizeattribute { protected override bool authorizecore(httpcontextbase httpcontext) { if (!httpcontext.user.identity.isauthenticated) homecoming false; // if user not authenticated, not allow string username = filtercontext.httpcontext.user.identity.name; string id = filtercontext.routedata.values[this.routeparameter]; if (username == id) homecoming true; // assuming paramter passed matches username, allow else if (filtercontext.httpcontext.user.isinrole( "admin" ) || isowner( filtercontext )) homecoming true; // if user has role admin, allow homecoming true; } }

while untested , meant guide more solve need, think come close implementation.

meanwhile, i'd add together 2 cents on approach:

i more in favor of action filter similar check , redirect user own page or warning page. while value security authorization filter provide, find them rather blunt. prefer permission based security , soft redirects provide more elegant user experience.

asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 authorization

No comments:

Post a Comment