Search code examples
corsfetchopenid-connectkeycloak

Silent authentication CORS problem when using Keycloak


I'm trying to perform Silent Authentication on my site using the following call:

fetch('http://localhost:8100/auth/realms/master/protocol/openid-connect/auth?response_type=code&scope=openid&client_id=portal&redirect_uri=http%3A//localhost%3A8080/o/auth/oidc/callback&state=CJOREX0_bHtivjgNUYRkE3908LqdnUUvm2Jhxo5U8tg&nonce=MJj2eQkCtlwqIx0UbSFdWRsbll7fiBSUkRkbxzi2VFs&prompt=none', {
    method: 'GET',
    mode: 'cors'
})

I have configured web origins for my client as follows: web origins

But I'm still getting CORS error:

Access to fetch at 'http://localhost:8100/auth/realms/master/protocol/openid-connect/auth?response_type=code&scope=openid&client_id=portal&redirect_uri=http%3A//localhost%3A8080/o/auth/oidc/callback&state=CJOREX0_bHtivjgNUYRkE3908LqdnUUvm2Jhxo5U8tg&nonce=MJj2eQkCtlwqIx0UbSFdWRsbll7fiBSUkRkbxzi2VFs&prompt=none' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Any idea what am I missing here?


Solution

  • The whole approach was a mistake here. I was trying to use Authorization Code flow from the client, which is not how it should work. Authorization Code flow is always about server to server interaction with client side redirects.

    If you'd like to use it, you will need to open the target page in an iframe or a separate page (for silent authentication, an invisible iframe will do).

    If your goal is to have pure client-side authentication you'd rather consider using Implicit (which is classic and simple, but is not currently recommended for security reasons) or Authorization Code with PKCE flows.

    There are many resources regarding auth flows, but if you'd like to see quick and high-level overview of them, I recommend to check this short article: https://dev.to/hem/oauth-2-0-flows-explained-in-gifs-2o7a