I have an action method and posting to it using ajax like this:
$.ajax({
url: "/GetSearchCriteria",
type: "GET", //these is must
cache: false, //these is for IE
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
VehicleId : vehicleId
},
}).done(function (data) {
debugger;
$('#myModal').modal('show');
});
I have defined action method like this:
[AjaxAuthorize]
[GET("GetSearchCriteria")]
public ActionResult GetSearchCriteria(VehicleSearchModel model)
{
return Json(model , JsonRequestBehavior.AllowGet);
}
and Authorize method for ajax requests like this:
public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext context)
{
if (context.HttpContext.Request.IsAjaxRequest())
{
var urlHelper = new UrlHelper(context.RequestContext);
context.HttpContext.Response.StatusCode = 403;
context.Result = new JsonResult
{
Data = new
{
Error = "NotAuthorized",
LogOnUrl = "/Login" //urlHelper.Action("LogOn", "Account")
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
base.HandleUnauthorizedRequest(context);
}
}
}
and then this javacript code:
$(function () {
$(document).ajaxError(function (e, xhr) {
debugger;
if (xhr.status == 403) {
var response = $.parseJSON(xhr.responseText);
window.location = response.LogOnUrl;
}
});
});
1). I see that most of times this authorize attribute is not hit. 2). Even If it is hit, then user is redirected to logic page but no return url is appended to url. 3). Any user can login( even if he is not authorized to login. I want only users with Role Customer to login other wise to redirect them to not authorized page.
Please suggest how to do it.