Formsauthenticate + jQuery Ajax

Asked

Viewed 42 times

0

I am creating an application that uses Formsauthenticate to log into the system.

However, I would like to make a treatment so that in an ajax request (jquery) made when the user is not logged in.

I put a $(document).ajaxComplete(function (event, xhr, settings) {})). However, when the server informs that there is no login and gives a redirect to the login page, the xhr.status is returned as 404.

Doing some research, I found this site. The solution given with ApplicationAuthorizeAttribute:HandleUnauthorizedRequest is just what I was imagining.

The main class is as follows:

public class ApplicationAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        var httpContext = filterContext.HttpContext;
        var request = httpContext.Request;
        var response = httpContext.Response;
        var user = httpContext.User;

        if (request.IsAjaxRequest())
        {
            if (user.Identity.IsAuthenticated == false)
                response.StatusCode = (int)HttpStatusCode.Unauthorized;
            else
                response.StatusCode = (int)HttpStatusCode.Forbidden;

            response.SuppressFormsAuthenticationRedirect = true;
            response.End();
        }

        base.HandleUnauthorizedRequest(filterContext);
    }
}

I just don’t know how to put this in my code. (my English is not very good). Has some way this class is automatically loaded so that Overriding can be executed?

1 answer

0


I got. First, I removed from the web.config the "<authorization>" leaving only the "<authentication>"

<authentication mode="Forms">
  <forms loginUrl="~/Login" name="nome"></forms>
</authentication>

Once the class mentioned in the question is created, the attribute "Applicationauthorize" will be created and can be used.

From there, I put in the classes/methods that I want the user to be logged in to access them, the attribute. For example:

[ApplicationAuthorize]
public class HomeController : GlobalController
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
}

With this, only logged in users can access the Home.

This also helped me to do a control in jquery for AJAX requests made when the user loses the session, for example. AJAX gets a 401 status (not a 302 followed by a 200 html login page, as was happening before)

Browser other questions tagged

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