Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How may I best use the [Authorize] attribute with Ajax and Partial Views?

I was about to use [Authorize] on Actions that return partial views through Ajax; but I'm not getting the behavior I'd like (although its the behavior I expected).

It seems like a long shot; but, is there any way to extend this attribute to "break out" of an AJAX call and redirect the entire page to the login screen? (As opposed to returning the login screen to whatever location I've set UpdateTargetId?)

I think I have a handle on how I'd do this on each of the specific Ajax calls, but if I could centralize this somehow, it'd save a lot of code...

like image 241
Professional Sounding Name Avatar asked Apr 13 '09 07:04

Professional Sounding Name


1 Answers

AuthorizeAttribute won't do this for you, but you can centralize your code. Create a new attribute which returns http status code 401 (not authorized) when no user is currently logged in. In a JavaScript file referenced by your site.master, handle the jQuery $.ajaxError event. Look for http 401 in the response status code and redirect to your login page via JavaScript. Now any Ajax call which you make via jQuery will end up here if the current user is not authorized.

like image 92
Craig Stuntz Avatar answered Oct 14 '22 00:10

Craig Stuntz