morgan9999
morgan9999

Reputation: 801

Keycloak authentication blocked by CORS

I am trying to use Keycloak Javascript adapter in my React application, however after redirected from login page, it doesn't authenticate me, instead its giving me CORS error

Access to XMLHttpRequest at 'http://auth.keycloak.local/auth/realms/sso/protocol/openid-connect/token' from origin 'http://192.168.0.5:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

this is my Javascript page

import React from 'react';
import './App.css';
import Keycloak from 'keycloak-js';

const initKeycloak = async () => {
    const keycloak = new Keycloak({
        realm: 'sso',
        url: 'http://auth.keycloak.local/auth/',
        clientId: 'sso-management',
    });

    try {
        const isAuthorised = await keycloak.init({ onLoad: 'login-required' });
        console.log(isAuthorised);
    } catch (error) {
        console.log(error);
    }
};

function App() {
    initKeycloak();
    return (
        <div className="App">
            hello world
        </div>
    );
}

export default App;

and this is my keycloak client configuration enter image description here

Am I missing something?

I'm using nginx reverse proxy on my local machine for the keycloak server if that makes any difference

Upvotes: 6

Views: 14202

Answers (1)

morgan9999
morgan9999

Reputation: 801

Apparently in this particular case, I need to pass client secret when connecting to keycloak server since the client "access type" is "confidential".

To be able to make the code above work is to change the "access type" field to "public" and that will solve it.

I have no idea why the error response to the browser is CORS error which is absolutely unrelated on first glance from my perspective.

I figured it out after trying to make a request using Postman to http://auth.keycloak.local/auth/realms/sso/protocol/openid-connect/token with the same body message, and in postman it returns more relevant error which is asking me to provide client secret

Upvotes: 3

Related Questions