Can you explain the differences between HttpApplication.AuthenticateRequest and HttpApplication.AuthorizeRequest in ASP.NET MVC 3 please? When will they occur? Assume this scenario:
My User has a property called IsBanned and I want to check his/her IsBanned property in each request. If it was true, I redirect the User to an error page. But not for all requests, just requests that their action signed by [Authorize] attribute. OK, atthis type of actions, will HttpApplication.AuthenticateRequest occur or HttpApplication.AuthorizeRequest or anything else?
I know I can check this property in SignIn|LogOn action. But I means this:
A user requests logging in
I check the property IsBanned and it was false
The user logged in
User view some pages of site
The admin banned the user (while he is logged in)
User requests a page (action) that have [Authorize] attribute
User is logged in (before this. remember?)
So I have to show the requested page
But the user give a banned flag by admin
How can I prevent user from viewing requested page?
Thanks in advance.
I dont think you need to deal with either of HttpApplication.AuthenticateRequest or HttpApplication.AuthorizeRequest. I would solve it by using a custom Authorize Attribute.
public class MyAuthorizeAttribute : AuthorizeAttribute {
protected override bool AuthorizeCore(HttpContextBase httpContext) {
bool authorizerPrimarily = base.AuthorizeCore(httpContext);
if(authorizedPrimarily){
return user_not_banned;
}
return authorizerPrimarily;
}
}
You can get user's name from httpContext.User.Identity.Name. Use it to grab data from database.
Update for comment-1
To redirect banned users to a specific page, you may do this:
if(authorizedPrimarily){
if(user_banned){
httpContext.Response.Redirect("url of banned message");
return false;
}
return true;
}
Related
This is a mvc application
I have the links below on my master page
Link1 Link2 Link3 signout signIn
I have a userprofile object that is populated
when authentication is done.
When the session object for the user expires
and I click on the links, I get the yellow page(error page).
I will prefer a situation where when you click on the
links and the session object is expired, you get
redirected to the signin page.
Soln A: I could solve this problem by writing a method
which test for null value of the userprofile object then
make a call to this method on the click on every link.
I dont want this approach because in the future if there
are new controllers, i will need to care for them.
Do you have any idea how I can solve this problem?
I would have a Base Controller than all of your other controllers inherit from. Within this I would have a
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (SessionManager.Instance() == null)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{ "Controller", "BaseController" },
{ "Action", "LogOn" }
});
}
base.OnActionExecuting(filterContext);
}
The OnAction Executing will be hit before any method in any of your controllers - this way you can check your session is valid or your user is valid or whatever and handle the redirect to the view you want if that is not the case. If you do a Google search for Filters Actions MVC you will find out much more info.
I have written a custom AuthorizeAttribute to display message in the login page. Here is the code.
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public string Message { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
httpContext.Items["LoginFailMessage"] = Message;
}
return authorized;
}
}
In my action I will do
[MyAuthorize(Message = "Please login to continue")]
public ActionResult Detail()
Now, I cannot access the item HttpContext.Current.Items["LoginFailMessage"] in my view. I realize that the problem is, the item exists only for one redirection call but authorization failure is causing more than one redirection.
So, is there a way I can solve the issue? From exactly where should I pass the message?
Edit
What I am trying to do is, suppose, an Anonymous user is allowed to see a short description of something.
With the description, there is a edit and a detail link. Both edit and detail requires the user to login. So, the user will be redirected to login page if clicks either.
If user clicks edit I will display a message Please login to edit and if clicks detail may be please login to see detail in the login page.
It would be much easier for you to use the ModelState to do this, for example:
[HttpPost]
public ActionResult Login(LoginViewModel model) {
// .. check model state is valid
if (AuthorizationService.Authorize(model.Username, model.Password)) {
// .. user is authenticated
}
else {
ModelState.AddModelError("", "Login failed.");
return View(model);
}
}
Then you can use the ValidationSummary() to show the error on the login page, or, pass the name of the username or password model property in the AddModelError call to use a ValidationMessage().
Is there an integrated way in asp.net mvc 3, to permit authentification and actions based on the time of the day ?
For example, if it's 18:00 o'clock, users that belong to a specific role are not allowed to log in or if they are already authenticated, they will be automatically logged out or not being able to do actions.
I guess in the log in method I could check for user role and time of day and then on each action, I will also check for role and time of day and permit but is there and easier way to accomplish this ?
UPDATE:
I guess there is no easier way to just set the time and user/roles so I ended up implementing the answer(solution).
You could write a custom Authorize attribute and override the AuthorizeCore method in which you would perform the necessary check:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
if (!authorized)
{
return false;
}
// At this stage standard authorization passed =>
// you could now check the user roles in the database
// and the time of the day and return true or false from here
...
}
}
and now all that's left is decorate your controllers/actions with this custom attribute.
For certain actions like changing email settings or administrator activities, I want users to re-authenticate before the action is completed. Is there a good pattern for doing this in ASP.NET MVC 3?
Descpription
You can create your ActionMethod with Username, Password and the field you want to change (Email) for example. Than validate this data in the [HttpPost] of your data. If the authorization has success, change it and if not add the error to the ModelState.
Use a ViewModel for that.
Sample
public class ChangeEmailViewModel
{
public string Username { get; set; }
public string Password { get; set; }
public string EmailAddress { get; set; }
}
public ActionResult ChangeEmail()
{
return this.View(new ChangeEmailViewModel());
}
public Action ChangeEmail(ChangeEmailViewModel model)
{
// authorize
bool isAuthorized = // your logic.
if (isAuthorized)
{
// change email
} else
{
ModelState.AddModelError("Username", "Username is not valid");
}
return this.View(model);
}
If you want to dynamically intercept and re-authenticate someone who is already authenticated, you could probably also handle this with a special cookie. The actions that require re-auth could be decorated with a custom filter that overrides OnAuthorization to check for the cookie, then redirect to take username & password if it is not found. Pattern, no code:
User clicks link to uber-protected action.
Filter on action looks for cookie and does not find it, redirects to sign in.
User signs in, and you write a special cookie
(different from the forms auth cookie),
then redirect back to original action.
Filter on action looks for cookie and finds it authorizing user.
The lifetime of the cookie would at least have to go all the way to the http post of the uber-protected action. You will have to decide when to delete it. For example, after user re-auths for one uber-protected action, do you want them to re-auth for second uber-protected action in the same browser session?
I have noticed that if a user is still logged in or has a persistent cookie, even if he gets "banned", or disabled in the database (Users Table flags), the user can still access everything until that cookie goes away or the user logs out of the site. Great security right.
So I am putting together a ActionFilterAttribute that checks for this, the disturbing thing for me is I have to hit the database for every controller that his ActionFilterAttribute is applied to. There has to be a better way of doing this but I have not found one yet.
Any ideas would be awesome..
There has to be a better way of doing this but I have not found one yet.
No there isn't. Sorry. If the notion of disabled/banned user exists only in your database there is no other way but hitting your database. ASP.NET only verifies the validity of the authentication cookie which is sent on each request. It doesn't even know what a disabled user means so you cannot expect it do more than it already does.
There are a few options:
1) You can validate whether the user authentication is valid by hooking session start. This way if the user has a persistent cookie, you can validate the username and expire the cookie if needed.
2) You can use a time based mechanism to check the user auth status every few requests (every 5mins or whatever). You could store the lastChecked timestamp value in the user session or in the auth cookie itself using the UserData field. This allows you recheck if the user auth cookie needs to be expired more frequently, but keeps database calls to a minimum.
MyThis is the solution I came up with:
In the User Account Membership service add a function to return whether the user's account is still active.
public class UserAccountMembershipService : IMembershipService
{
public bool UserIsActive(Guid userId)
{
if (userId == new Guid()) throw new ArgumentException("Value cannot be null or empty.", "userName");
MembershipUser user = _provider.GetUser(userId, true);
return user.IsApproved;
}
}
Override the AuthorizeAttribute as follows:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
IMembershipService membershipService = new UserAccountMembershipService();
//Check to see if the user's account is still active
bool isActive = false;
if (httpContext.User.Identity.IsAuthenticated)
{
Guid userId = (Guid)Membership.GetUser(httpContext.User.Identity.Name).ProviderUserKey;
isActive = membershipService.UserIsActive(userId);
}
if (!isActive)
{
//If the user's account is no longer active log him/her out
IFormsAuthenticationService FormsService = new FormsAuthenticationService();
FormsService.SignOut();
}
//Call the base AuthorizationCore method
return base.AuthorizeCore(httpContext) && isActive;
}
}