How to redirect to another page when user does not have authorization

Asked

Viewed 982 times

0

I have my Custom AuthorizeAttribute.

It works perfectly the way I want, but it always directs the user to /Account/Login, I would like you to redirect to another page that I choose, since it has no authorization, how do I do this?

Remembering is Authorization and not authentication.

In authentication the page is correct, do the login.

  • http://meta.pt.stackoverflow.com/questions/297/quando-se-deve-colocaro-nome-da-linguagem-no-t%C3%Adtulo/1911#1911 Please collaborate on formatting, you are being greatly benefited on the site and could help keep posts organized. http://meta.pt.stackoverflow.com/questions/1084/como-devemos-formatar-perguntas-e-respostas/1297#1297

  • ok @bigown, I put in the title because I forgot the tags, sorry

2 answers

1

Based on that question.

Add the following method to CustomAuthorizationAttibute:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (string.IsNullOrEmpty(System.Web.HttpContext.Current.User.Identity.Name))
        {
            // A sessão está nula ou vazia, não existe usuário logado.
            filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary(
                new
                {
                    controller = "Home",
                    action = "Login"
                })
            );
        }
        else
        {
            // Usuário não tem permissão.
            filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary(
                new
                {
                    controller = "Home",
                    action = "NaoAutorizado"

                })
            );
        }
    }

0

Redirect normally using the MVC Redirect Method.

And put a Location tag on the web.config assigning anonymity to your action only (url)

<location path="login/SessaoExpirada">
    <system.web>
        <authorization>
            <allow users="?" />
        </authorization>
    </system.web>
</location>
</configuration>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.