1

I have configured keycloak server installed and configured. My application consists of single html page deployed on apache HTTP server which is on same machine as on keycloak server. This HTML page makes an REST json ajax call to fetch data. HTML page is secured using JS adapter and rest service are exposed using a spring boot application and secured using spring boot adapter.

Keycloak has a single client for which client adapters are configured.

Now, the js adapter works perfectly file. It redirects to login page and after login , it redirects to the required page. Spring boot adapter also works fine. When we do a GET for the web service , it redirects to login page and after entering the credentials the web service serves the response.

Problem is when the HTML page makes call to this web service using AJAX , it fails.
So when i enter credentials in key cloak server and when redirected to html page, the html page fails to make a ajax call. Response code is 302 and its redirected to the keycloak auth service(during ajax call).

My question here is :
* If my html page and restful web service use the same keycloak client, shouldn't i need to login once? * If both (html and webservice ) are authenticated seperately and are working file, then why its not working when i just login to html page?
* Is there a different way to overcome this issue?

sideshowbarker
  • 62,215
  • 21
  • 143
  • 153
Snake Eye
  • 525
  • 3
  • 13

1 Answers1

1

The solution was pretty simple. I had to use jsonp instead of json ajax request.
I added dataType:"jsonp" in ajax call and used spring 4 advice to support the jsonp support on server side.
Advice code :

@ControllerAdvice
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
public JsonpAdvice() {
    super("callback");
    }
}

Javascript code:

$(document).ready(function() {
$.ajax({
    url: "http://localhost:8081/hello-world/",
    dataType:"jsonp"
}).then(function(data) {
   $('.greeting-id').append(data.id);
   $('.greeting-content').append(data.content);
});

});

Following Link helped me a lot :

Why is jquery's .ajax() method not sending my session cookie?

Community
  • 1
  • 1
Snake Eye
  • 525
  • 3
  • 13