In my MVC3 project, I have a controller with an [Authorize] attribute.
I have a form submission without ajax, which redirects the user (as expected) to the login screen, if he/she is not logged in.
However, now I have a form which is submitted with jquery ajax, and how can I do the same thing? Redirect the user to the login screen, if he/she is not authorized? After a successful login, the user should is redirected to the initial action.
Controller
[Authorize]
[ValidateInput(false)]
public JsonResult SubmitChatMessage(string message)
{
if (!string.IsNullOrEmpty(message))
{
// Do stuff
}
// Return all chat messages
return GetChatMessages();
}
Client JQUERY
$(document).ready(function () {
$("form[action$='SubmitChatMessage']").submit(function (event) {
$.ajax({
url: $(this).attr("action"),
type: "post",
dataType: "json",
data: $(this).serialize(),
success: function (response) {
// do stuff
}
});
return false;
});
});
I can see from firebug console window, that the server returns:
GET http://domain/Account/LogOn?ReturnUrl=%2fProductDetails%2fSubmitChatMessage
Looking forward to your help!
UPDATED with possible solutions
Yep, this is one of things i’ve always hated about Forms Authentication in ASP.NET – does not cater for AJAX authentication at all. Add IIS handling 401’s into the mix, and it can be quite a pain.
There’s a few ways to do this, none of them particulary “clean”.
These include:
Set a ViewBag flag in the controller, which corresponds to
Request.IsAuthenticated, then re-write the submit button click event to the login page if they’re not authenticated.Make your AJAX action return
JsonResult, which a property for “code”. Where a code of 0 can be success, 1 can be unauthenticated, 2 can be some other data issue, etc. Then check for that code in thecomplete$.ajaxcallback and redirect to the login page.Check the
$.ajaxjqXHRresponse object for a status code of403, and redirect to the login page.Write a custom HTML helper for your submit button, which renders either a regular submit button, or a anchor tag which goes to the login page, depending on the authentication status.
Write a custom authorize attribute which checks if
Request.IsAjaxRequest(), and returns a custom JSON object, instead of the default behaviour which is to redirect to the login page (which can’t happen for AJAX requests).