ASP.NET MVC: Custom parameters to login page after authorization - asp.net-mvc

I would like to redirect visitors to a login page with added parameters (based on the action they are performing) after the authorization fails.
This is an example of what I would like to do:
ASP.NET MVC - CustomeAuthorize filter action using an external website for loggin in the user
However, since this is a custom filter, I do not know how or if I can specify the Roles like in the usual authorization filter. I would like something like:
[CustomAuthorization(Roles="Admins")]
Thank you!

You could inherit from AuthorizeAttribute class and override OnAuthorize method like this:
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (!HttpContext.Current.User.IsAuthenticated)
{
filterContext.Result = new RedirectResult("target");
}
}
Then you can use this custom filter just like AuthorizeAttribute.

Have you tried downloading the ASP.Net MVC source and taking a look at the AuthorizeAttribute's code (in AutorizeAttribute.cs)?
It might make sense to derive your CustomAutorization from the existing AuthorizeAttribute - check it out and see if you can tack on your required functionallity.

What about using just Request.Form in your custom Authorization class. It is just a POST call after all? Don't make it harder than it actually is.

Related

How to choose suitable filters in ASP.NET MVC for this scenario?

I understand different types of filters are available in ASP.NET MVC. Now I am confused about the following 3 types of filters. I have to use custom filters in my code.
Authentication Filter
Authorization Filter
Action Filter
I have users, roles and their permissions (read, add, delete) in 4 different tables.
Which filter method I should choose?
When I did a search, I am able to found some of them using Action filters as
public class MyFirstCustomFilter : ActionFilterAttribute
{
....
}
OnActionExecuting - my code goes here for role and permmsion - is this correct way ?
OnResultExecuting
But some article use
public class CustomAuthAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
//my code goes here for role and permission check - is this correct way ?
}
}
I want to check user is eligible to execute particular action based on roles & permission in db.
Now I am confused with all these methods. For me, all are similar. Correct me if I am wrong.

OverrideAuthentication attribute not working? ASP.NET MVC 5

I have a super simple Authentication Attribute that I'm trying to implement in an ASP.NET MVC 5 application and I'm having some trouble. I want the attribute to be applied globally, except for specific actions within a controller (for example the login form and the home page).
I've tried decorating the action with the [OverrideAuthentication] attribute with no luck. It gives me a redirect loop error because the application is still running the authentication on the login form, and keeps trying to redirect back to the login form over and over.
Has anyone else seen this behaviour? Any idea what I've stuffed up here?
By way of example, I've created a super simple filter that is currently unimplemented:
public class BasicAuthenticationAttribute
: ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
throw new NotImplementedException();
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
throw new NotImplementedException();
}
}
If I decorate my controller/action like this:
[BasicAuthentication]
public class AccountController : Controller
{
[HttpGet]
[OverrideAuthentication]
public ActionResult Login()
{
return View();
}
}
I get a not implemented exception when I navigate to the Login action, even though that action shouldn't be running the authentication code at all. Have I misunderstood how overrides are supposed to work?
I think you have confused authentication with authorization (as many people do). It doesn't make sense to make a [BasicAuthenticationAttribute] and register it globally, because authentication only happens upon login, not on every request.
Authorization is what takes place after the user has logged in to check whether the user has the required privileges to do a specific action, and it makes sense to do authorization globally. Authorization in MVC is handled by the [AuthorizeAttribute] and you can inherit it if you need to customize the way the authorization check is done. You can also register it as a global filter.
The [AllowAnonymousAttribute] works in conjunction with [AuthorizeAttribute], and basically tells it to skip the authorization check. It should also be noted that the [AllowAnonymousAttribute] will have no effect unless it is used with the [AuthorizeAttribute].

What is Webform's "UrlAuthorizationModule.CheckUrlAccessForPrincipal" equivalent for MVC?

I got a problem as i am writing a custom SSO solution for my company. To mkae it simple, i've made a custom authentication httpmodule that intercepts all requests so as to check user authentication state. If not authenticated, user is redirected to my custom sso login page.
The thing is, when user is not authenticated, i'd like to check if he can access the requested page/resource... With Webforms, no problem, i add an authorization block in web.config, and i use UrlAuthorizationModule.CheckUrlAccessForPrincipal with an anonymous user. Everything works fine...
But when i apply my module to an MVC (3) web site, this does not work anymore (for obvious reasons, like the possibility to access the same controller and/or action from differents urls when using routing, and because authorizations are made through controller attributes).
How can I achieve this ?? I've been searching all day long, didn't find anything about that :/
ASP.NET MVC 3 Internet Application template includes a basic AccountController which implements the following actions (along with the associated models and views):
LogOn
Register
ChangePassword / ChangePasswordSuccess
You simply need the [Authorize] attribute on the Actions or classes you wish to secure. But if you need something really custom you can do something like I've done.
I created a custom class to override security in my application.
public class AuthorizeActivityAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
HttpContext currentContext = HttpContext.Current;
//Do your custom authentication stuff here and return true or false depending on results
Return true;
}
}
And now in my Controller I have the following:
[AuthorizeActivity]
public ActionResult Index()
{
ViewBag.Message = "Welcome";
return View();
}
I had the same problem.
See solution here: MVC equivalent of Webforms "UrlAuthorizationModule.CheckUrlAccessForPrincipal"
You would have to read the information from the other controller. This
can be done by instantiating its context and the Descriptor, then
instantiating the AuthorizationContext for that controller and read
the filter info.

AuthorizeAttribute behavior in ASP.NET MVC when authentication mode is set to Windows

I have a controller protected with AuthorizeAttribute. When the authorization fails i get just an empty page. If i override OnAuthorization() i can see that after calling base.OnAuthorization() filterContext.Result is null (why?). If i override OnException() and set a breakpoint it never hits. Can please someone explain how it's supposed to work? How can i make it redirect to specified page? Where can i inject into to log failed authorization attempts (better not to write custom filter)? I use MVC 3 RC1 if it's important.
You want to override the AuthorizeAttribute.HandleUnauthorizedRequest method. Here's the default implementation:
protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
// Returns HTTP 401 - see comment in HttpUnauthorizedResult.cs.
filterContext.Result = new HttpUnauthorizedResult();
}
You'll instead want to set the Result to be a RedirectResult (or some other result depending on your desired logic). This would also be a good place for logging.

ASP.NET MVC 1.0 Authentication

I realise that I can prevent unauthenticated users from accessing views at controller level by applying the [Authorize] attribute and can also filter views down to individual users or roles using this. However, my question is regarding doing the opposite... Is there a way to deny authenticated users from certain views without having to manually add in checks to see if they're authenticated in the opening lines of the controller code? Ideally an [Unauthorized] attribute or an equivalent if such a thing exists?
The reason for this is that I don't want authenticated users to be able to visit the account creation pages of the site I'm working on, as well as other resources. I realise I could check them in the controller explicitly but I'd prefer to decorate the controller methods if at all possible.
Thanks :)
This is along the lines of what LukLed was referring to:
public class UnAuthorizedAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
bool excludeCondition = false;
if (excludeCondition)
filterContext.Result = new HttpUnauthorizedResult();
else
base.OnAuthorization(filterContext);
}
}
Simply put in the logic for your excludeCondition. You can also to choose to do things like redirect to other views. Just mark your code with [UnAuthorized]
You can write your own authorization filter. Inherit from FilterAttribute and implement IAuthorizationFilter. Call it UnauthorizedAttibute and you will be able to use it like [Authorize].
Hear You can read about filters:
http://www.asp.net/LEARN/mvc/tutorial-14-cs.aspx
A simple way to accomplish this? Just leave the action untagged, and start with:
If(Request.IsAuthenticated)
// redirect somewhere, or return another view...
this could also be accomplished fairly simply if you are already using a roleprovider. then your actions would just need to be filtered by the appropriate role:
[Authorize(Roles = "Admin, Editor")]

Resources