getting Roles that already set to custom Authorization attribute? - asp.net

I customized the authorize attribute of Asp.Net but I do not know how to get the roles which I set to the attribute when I set the attribute to a method or class
For example I have this CustomeAuthorizeAttribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomeAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.IsInRole("Super"))
{
return true;
}
else
return false;
}
}
but I do not know how to get the roles when I set them to the attribute like this
[CustomeAuthorizeAttribute(Roles="admin,super-admin")]

by default it inhirits the Roles property from the base Authorize class so you can get the roles directly by using the Roles property
For Example
if (HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.IsInRole(Roles))
{
return true;
}
or you create new properties belong to your custom Authorization attribute and use them.

Related

AuthorizeAttribute Redirect After user Login

I am using default Web Application template for MVC4 in Visual Studio. How can I write Authorize Attribute to redirect user after succesfull login? This attribute should look like this: [UserRedirect("username")] whether anyone use "username" login redirect should be made. Where do I apply this attribute? To the login page or index? Thanks for answer.
You need to override OnAuthorization method of AuthorizeAtribute
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class UserRedirectAttribute: AuthorizeAttribute
{
public string UserName{ get; set; }
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.onAuthorization(filterContext);
if(base.AuthorizeCore(filterContext.HttpContext) == true)
{
//here put all the a logic for redirect condition ()
if(filterContext.HttpContext.User.Identity.Name.Equals(this.UserName,StringComparer.Ordinal)
{
//if you should do the redirect
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Redirect controller name",
action = "Redirect action name"
})
);
}
}
}
}
Regarding the usage:
If it is an authorize attribute that is going to replace default authorize attribute you should on any authorized Action/Controller
EDIT:
Based on your last comment you don't have to use an attribute at all. Just add the redirect logic at the end of your login action:
[HttpPost]
public ActionResult Login(LoginModel model)
{
bool userAuthenticationResult = // here goes your authentication logic
if(userAuthenticationResult && HttpContext.User.Identity.Name.Equals(this.UserName,StringComparer.Ordinal))
{
//setup cookie/token any other things you need for the authentication to work
return RedirectToAction("ActionName","ControllerName");
}
}

Can be rewritten the custom attribute parameter defined in controller (ASP.NET MVC3)?

I have some actions defined in controller which modify file content (of course, I don't modify directly from controller but this controller calls the methods from model). Over that function, I put a custom attribute which mention that must have admin rights.
The action looks like:
[CustomAttribute(MustBeAdmin = true)]
public ActionResult ModifyFile(){
...
}
and CustomAttribute looks like:
public class CustomAuttribute: AuthorizeAttribute
{
public bool MustBeAdmin {get;set;}
protected override void HandleUnauthorizedRequest( AuthorizationContext filterContext) {
if ( filterContext.RequestContext.HttpContext.Session["user"] == null ) { ... }
else { ... // check if is need admin rights and current has this right then continue else go to default route }
}
}
I want to ask you, for security purpose, if someone can set MustBeAdmin parameter to false value from outside of code ?
If yes, how to prevent this ?
Thanks

MVC3 Extra role attribute

I'm creating a website where an Admin can add Teachers and Students, the admin should be able to specify what the Teacher can do when he's in a particular Location.
Is it possible to extend the Authorize attribute to check in what Location the specific user is in? for example [Authorize(Roles = "Administrator", Location="ICT")] ?
And if so, how can I extend this?
Thanks in advance.
And if so, how can I extend this?
By writing a custom authorize attribute:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public string Location { get; set; }
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
var result = base.AuthorizeCore(httpContext);
if (!result)
{
return false;
}
// At this stage we know that the currently logged in user
// is authorized. Now you could use the Location property
// to perform additional custom authorization checks and
// return true or false from here
string user = httpContext.User.Identity.Name;
...
}
}
and then:
[MyAuthorize(Roles = "Administrator", Location = "ICT")]
You can create Your own custom authorize attribute.
See video here asp-net-mvc3-custom-membership-authorizeattribute-tutorial

ASP.NET MVC3: custom [authorise] attribute

In my database, the system user has a list of modules he/she can access.
I would like to be able to add an authorise attribute which checks that this is the case.
E.g. [authorise(UserID, ControllerName)]
Which goes to some code, ensures that the User with UserID specified, has the controller name in his/her list.
At the moment you can simply bypass the fact the tabs aren't visible, by using the URL. (I have code which already checks if the user has specified access and hides/shows tabs)
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
string currentUser = httpContext.User.Identity.Name;
string currentController = httpContext.Request.RequestContext.RouteData.GetRequiredString("controller");
// TODO: go hit your database and see if currentUser can access
// currentController and return true/false from here
...
}
}
then decorate your controllers or actions:
[MyAuthorize]
public class FooController: Controller
{
...
}
This being said I suspect that you might have gone the wrong way in your database design by storing a list of which user has access to access which controller action. Probably you should have used roles for that. Having the database know about controllers just feels wrong.
So:
[Authorize(Roles = "Foo,Bar")]
public class FooController: Controller
{
...
}
Only users that have the Foo or Bar role can access the FooController.
You can create a new attribute.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class CustomAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new HttpUnauthorizedResult();
}
bool authorized = // Perform custom logic
If(!authorized)
{
filterContext.Result = new RedirectResult(/* Your access denied url */);
}
}
}
When you create the model, check the permission
DisplayAdminLink = _permissionService.Authorize(StandardPermissionProvider.AccessAdminPanel),
and in the view
#if (Model.DisplayAdminLink)
{
<li>#T("Account.Administration")
</li>
}

restrict user access to controller based on property in object (asp.net mvc)

What is the best way to control user access to a controller. I have local User object with a property(boolean - "IsSubscribed"). Users can only access the controller if the value is true.
Notes:
I use forms authentication, but NO .net membership/profile etc.
mvc version 2
You could write a custom Authroize attribute:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
// Perform your custom authorization and return true/false
}
return isAuthorized;
}
}
and then decorate your controller/actions with this attribute.

Resources