0
votes

How can I redirect user after successful login to specific page. I need to do this by Authorize Attribute. In my problem I have to redirect user to page: Index/About when he/she would use specific login name, rest of users would be redirected to Index/Home.

I try this method:

public class AuthAttribute : AuthorizeAttribute
{
    private string userName;

    protected override bool AuthorizeCore(HttpContextBase filterContext)
    {
        var authorized = base.AuthorizeCore(filterContext);

        if (!authorized)
        {
            return false;
        }

        string userAuthenticated = filterContext.User.Identity.Name;
        bool specialUser = userName.Equals(userAuthenticated,    StringComparison.OrdinalIgnoreCase);

        if (specialUser)
        {
            filterContext.Items["RedirectToHomeAbout"] = true;
            return false;
        }

        return true;
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (filterContext.HttpContext.Items.Contains("RedirectToHomeAbout"))
        {
            var routeValues = new RouteValueDictionary(new
            {
                controller = "Home",
                action = "About",
            });

            filterContext.Result = new RedirectToRouteResult(routeValues);
        }
        else
        {
            base.OnAuthorization(filterContext);
        }
    }

This is the code from account controller:

[Authorize] [InitializeSimpleMembership] public class AccountController : Controller { // // GET: /Account/Login

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {
            return RedirectToLocal(returnUrl);
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }

    //
    // POST: /Account/LogOff

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult LogOff()
    {
        WebSecurity.Logout();

        return RedirectToAction("Index", "Home");
    }

Thanks! MarQ

2
Can you also provide code where you login the user?ntl
Yes. I just added code from account controller. Thanksuser3957853
Ok, I've created answer with code example, please check.ntl

2 Answers

0
votes

Instead of override OnAuthorization, you might want to override HandleUnauthorizedRequest.

In this way, the code would look like:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {

    if (filterContext.HttpContext.Items.Contains("RedirectToHomeAbout"))
    {
        filterContext.Result = new RedirectToRouteResult(
                                   new RouteValueDictionary 
                                   {
                                       { "action", "About" },
                                       { "controller", "Home" }
                                   });
    }
    else
    {
        //your general redirect here
    }
}
0
votes

If I understand your requirement correctly you can do it in your AccountController:

    private string specificUserName = "specificUserName";

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
        {
            if (string.Equals(model.UserName, specificUserName))
            {
                return RedirectToAction("Index", "About");
            }
            return RedirectToAction("Index", "Home");
        }

        // If we got this far, something failed, redisplay form
        ModelState.AddModelError("", "The user name or password provided is incorrect.");
        return View(model);
    }