FormsAuthenticate + jQuery Ajax

0

I'm creating an application that uses FormsAuthenticate to login to the system.

However, I'd like to make a treatment for 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, xhr.status is returned as 404.

Doing a search, I found that site . The solution given with ApplicationAuthorizeAttribute : HandleUnauthorizedRequest is quite what I was imagining.

The main class follows: method

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 do not know how to put this in my code. (my English is not very good). Is there any way for this class to be loaded automatically so overriding can be executed?

    
asked by anonymous 10.11.2015 / 15:06

1 answer

0

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

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

Once the class named in the question is created, the "ApplicationAuthorize" attribute is 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 will be able to access Home.

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

    
17.11.2015 / 16:27