I want do do something similar to the following
if (Session["UserId"] == null)
{
RedirectToRoute("Default");
}
So that anyone that hasnt been granted a session (by my login page) will be kicked out to the login page. How would I do this so it happens on
1) selected actions of my choosing
2) all actions if need be
That’s the default behavior of the
[Authorize]attribute. So you could selectively decorate controller actions that requires authorization by this attribute:And if you want to apply it on multiple actions you could write a base controller and then decorate this base controller with the given attribute. Then all child controllers that derive from this base controller and all actions will require authorization in order to be accessed.
You also have the possibility to write a custom authorization attribute based on the specific requirements you might have. For example:
then decorate actions/controllers that need to follow this custom authorization logic with this attribute:
Now when you authenticate an user in your login action (which obviously shouldn’t be decorated with any authoraztion attribute), upon valid credentials, you would add the UserId property to the session and redirect to some other controller action that is itself decorated with this attribute and which requires authentication.
For most cases though, the default Authorize attribute is sufficient.