shiro pac4j cas ajax 401 when accessing another client

220 Views Asked by At

I am using cas 5.x.

I have cas-server and two web apps client-1 and client-2.

currently, I can single sign on and single sign out, but there is one problem in following steps:

  1. access client-1, it will ask me for login in cas server, then redirect me back to client-1 after login success.

  2. click one button to access the protected resources of client-2 via ajax in page of client-1, however this ajax call return 401.

if i access protected resources of client-2 from browser address bar directly in step 2, it works.

ajax cannot handle the redirect cause this problem, thus how to solve this problem?

my ajax call is :

//test() is in client-1
function test() {
            
    jQuery.ajax({
        url:"http://192.168.0.14:8445/client-2/user/userInfo",
        headers: {'X-Requested-With': 'XMLHttpRequest'},        
        success: function(res) {                    
            //...
        }        
    });
        
}
1

There are 1 best solutions below

2
On

Per the pac4j documentation,

When you're using an Indirect Client, if the user tries to access a protected URL, the request will be redirected to the identity provider for login. Though, if the incoming HTTP request is an AJAX one, no redirection will be performed and a 401 error page will be returned.

So what you're seeing is expected behavior.

Next, the HTTP request is considered to be an AJAX one if the value of the X-Requested-With header is XMLHttpRequest or if the is_ajax_request parameter or header is true. This is the default behavior/condition when handling/detecting AJAX requests, and by default, pac4j will only compute the redirection URL and add it as a header (assuming the addRedirectionUrlAsHeader is set to true for the indirect client) when it passes back the 401 http status.

ajax cannot handle the redirect cause this problem

It's not designed to handle the redirects. You need to catch the 401 in your AJAX call, take the redirect url from the header that is passed back to you and do the redirect yourself automatically, or do any other activity/action that is correct behavior for your application (display message, redirect to another URL, etc).