简体   繁体   中英

Ajax request after MVC authentication timeout/session cookie deleted

Using MVC 5 authentication when a user times out, or the session cookie cookie is deleted, the user gets redirected to the login page.

This works fine on full page loads, however for my Ajax calls this breaks client side. The redirect works as the authentication page shows up, but is unresponsive (behind the standard loading wheel).

I'm pretty sure this is some sort of JS issue.

JS:

$(function () {
    $('#dealSearchForm').on("submit", function (e) {
        e.preventDefault();
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (data) {
                $('#dealSearchForm').html(data);
            },
            complete: function (data) {
                $('#searchResults').show();
            }
        });
    });
});

Main View:

@{Html.RenderPartial("_DealSearch");}

<script src="@Url.Content("~/Scripts/DealSearch.js")"></script>

<script>

    $(document).ready(function () {
        @if (Model.Deals.Count > 0) {
            @Html.Raw("$('#searchResults').show();");
        }
    });

</script>

Partial View:

@using (Html.BeginForm("DealSearch", DealManagement, FormMethod.Post, new { @id = "dealSearchForm" }))
{
/* Search filters etc */

<div class="col-xs-7">
    <button id="button-search" class="btn btn-primary pull-right" type="submit" data-loading-text="Please wait...">Search</button>
</div>

<div id="searchResults">
    /* Grid with results */
</div>

Controller:

public virtual ActionResult Index()
        {
            var model = new DealSearchModel();

            return this.View(model);
        }

public virtual ActionResult DealSearch(DealSearchModel model)
        {
            // Get deals from service, uses search criteria
            model.Deals = GetDeals(model);

            // Return the view
            return PartialView(MVC.DealManagement.Views._DealSearch, model);
        }

I get errors client side:

错误客户端

If anyone has any ideas they'd be very much appreciated!

You have to override default behavior - I assume your problem is that when user hits an action, which needs authorization and currently his session has expired, AJAX response is no longer valid.

You didn't provide how you authorize your methods but consider creating custom authorize attribute:

public class CustomAuthorizationAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        // Check whether it is an AJAX or standard request
    }
}

How check whether it is an AJAX request you can find here . Instead of redirecting you should return 403 unauthorized result and handle it in your AJAX calls.

Using a method based on Kamos answer, I solved this using the following:

Custom attribute

public class AuthoriseAjaxAttribute : AuthorizeAttribute 
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.Result = new RedirectResult("~/Error/AjaxUnauthorized");
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

The /Error/AjaxUnauthorised View

@{
    Layout = ""; // Result of an ajax call
}

// Refresh the page, resulting in MVC default login/redirection
<script>
    $(document).ready(function($) {
        location.reload(true);
    });
</script>

// Only here for if Javascript is off
<div class="panel panel-default">
    <div class="panel-heading">
        <div class="row">
            <div class="col-xs-12">
                Authorisation timeout.
            </div>
        </div>
    </div>
    <div class="panel-body black-text">
        Please refresh the page and log back in.
    </div>
</div>

To the user this makes Ajax calls respond to a timeout in the same way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM