CORS configuration Keycloak for Angularjs

I’m setting up keycloak on my front with angularjs, and that’s currently setting it up.

 service.keycloak = new Keycloak({
                                  url: 'http://localhost:8200/auth',
                                  realm: 'master',
                                  clientId: 'bpms-dev'
                               });


                    service.keycloak.init({
                        onLoad: 'login-required',
                        enableLogging: true
                    }).then(function (auth){
                         if(auth){
                            var keycloak = service.keycloak;
                            
                            $window.location.href = '/main.html';
                         }else{
                            console.log("authentication failed");
                         }
                    }).catch(function(error) {
                         console.log('failed to initialize');
                    });

And authentication is successful, but when I redirect to url main, any call to my backend has the problem below. How to solve this?

obs: My configuration of Web Origin and Valid Redirect Uri for my client (bpms-dev) is:

Web Origins: http://localhost:4200
Valid Redirect Uri: http://localhost:4200/*

1 Like

That’s not a Keycloak localhost:8200 issue. Your backend localhost:4200 must have CORS headers enabled with origin http://localhost:4200 allowed.

Hi jangaraj, my backend its running in localhost:8180, and i configured CORS in my backend, but the request doesn’t even hit. Because of that, I suspect it’s some configuration on the front, or keycloak. Also, I configured an Interceptor for all frontend requests to go with these attributes in Headers (Image below)

I would recommend to study how CORS works Preflight request - MDN Web Docs Glossary: Definitions of Web-related terms | MDN

I don’t know you complete code, but I bet this is not very smart condition:

I bet your preflight request is not authenticated, so CORS headers are not returned, so browser stops all subsequent requests.

Also Access-Control-Allow-Headers: * sounds like copy&paste from Stackoverflow, without reading of documentation: Access-Control-Allow-Headers - HTTP | MDN

In requests with credentials, it is treated as the literal header name “*” without special semantics. Note that the Authorization header can’t be wildcarded and always needs to be listed explicitly.

So another bet for the problem if you have requests with credentials.

Again, this is not a Keycloak issue, so this is not a best forum to discuss your problem.

Thanks Jangaraj, my fear was that this was some configuration I didn’t do in Keycloak, but apparently that’s not the case.

I’m going to study this issue of CORS settings more.

Did you find the solution?