kenwarner
kenwarner

Reputation: 29120

Require re-authentication for certain actions

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?

Upvotes: 3

Views: 364

Answers (2)

danludwig
danludwig

Reputation: 47375

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?

Upvotes: 0

dknaack
dknaack

Reputation: 60506

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);
}

Upvotes: 2

Related Questions