6

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

Community
  • 1
  • 1
Nima
  • 937
  • 1
  • 13
  • 20
  • whats the point of an AJAX login if your just doing to redirect anyway? Why not just use a regular form? – RPM1984 Aug 01 '11 at 00:38
  • The point is, that logged in users should be able to submit some data to a controller with ajax. What to do, if they are not logged in? How to handle that scenario with jquery ajax? – Nima Aug 01 '11 at 08:57
  • right, my bad - i misunderstood. Answer added. – RPM1984 Aug 01 '11 at 23:48

2 Answers2

6

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:

  1. 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.

  2. 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 the complete $.ajax callback and redirect to the login page.

  3. Check the $.ajax jqXHR response object for a status code of 403, and redirect to the login page.

  4. 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.

  5. 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).

RPM1984
  • 72,246
  • 58
  • 225
  • 350
  • Thanks for the different solutions. I will update my question with other posts related to your answer, which gives a more detailed description of the different solutions. – Nima Aug 03 '11 at 08:38
  • Could you just do a redirect to action (to a session timeout or login screen?), in the C# function, if the user is not logged in? – nagates Jan 17 '12 at 18:49
0

It's a bit of a pain, to be honest. Even more so, in my opinion, if you're using Federated Identity, such as Windows Identity Foundation and/or Azure AppFabric Access Control Service.

Your Ajax calls can't handle the redirect.

My solution/suggestion is not to mark your Ajax-invoked controller action methods with [Authorize], but instead rely on the presence of some value that you insert into Session State from a controller action that does have an [Authorize] (typically the controller action method that was called to display the view). You know that the value can't have got into Session State unless the user was authenticated (and the session hasn't timed out). Fail the call to your Ajax method if this value isn't present, returning a specific JSON result that you can handle gracefully in your client-side code.

Using [Authorize] on an Ajax controller method causes weird, often hidden, errors (such as updates disappearing).

Steve Morgan
  • 12,978
  • 2
  • 40
  • 49
  • You are right, it is such a pain. It is actually a okay solution to use the session state, I will consider that. – Nima Aug 03 '11 at 08:37