KeyCloak : No 'Access-Control-Allow-Origin' header is present on the requested resource
Asked Answered
M

5

20

I'm using Angular 8.0.3 and keycloak 6.0.1 to make the front authentication.

Problem

I managed to get to the keycloak login page from my application. After logging in with my login details, an error occurs :
-localhost/:1 Access to XMLHttpRequest at 'https://localhost:8080/auth/realms/pwe-realm/protocol/openid-connect/token' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
-Keycloak init failed An error happened during Keycloak initialization.

Could you help me please ?

My Keycloak Configuration :

1 Realm : pwe-realm
2 client :
-pwe-api (for my back end)
-pwe-web (for my authentication front end)

pwe-web configuration:
Client Protocol: openid-connect
Access Type: public
Valid redicrect Uris: http//:localhost:4200/ (I tried also "*")

My code (I am using this librairy : keycloak-angular):

environments.ts :

import {KeycloakConfig} from 'keycloak-angular';

const keycloakConfig: KeycloakConfig = {
  url: 'https://localhost:8080/auth',
  realm: 'pwe-realm',
  clientId: 'pwe-web'
};

export const environment = {
  production: false,
  keycloakConfig
};

app.moudle.ts

//imports

const keycloakService = new KeycloakService();

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    KeycloakAngularModule,
    BrowserModule,
    AppRoutingModule,
    ...
  ],
  providers: [
    {
      provide: KeycloakService,
      useValue: keycloakService,
    }
  ],
  entryComponents: [AppComponent]
})
export class AppModule implements DoBootstrap {
  async ngDoBootstrap(app) {
    const { keycloakConfig } = environment;

    try {
      await keycloakService.init({ config: keycloakConfig });
      app.bootstrap(AppComponent);
    } catch (error) {
      console.error('Keycloak init failed', error);
    }
  }
}
Miran answered 24/11, 2019 at 14:17 Comment(0)
H
32

I wasted half a day on this while developing with Vue.js against a server on localhost.

You probably need to set the Web Origins on your Keycloak server for your Keycloak client:

  1. Login to the Keycloak admin screen, select the realm pwe-realm and then your client pwe-web.
  2. Scroll to the Web Origin settings and type the plus sign. Do not click on the (+) button, but literally type + . That adds all the Valid Redirect URIs that you defined above to the Web Origins headers. You will also need to add the URI of your angular application to the Valid Redirect URIs list.
  3. Press Save at the bottom of the screen.

It should work immediately.

Handal answered 27/11, 2019 at 14:27 Comment(6)
Woah ! Thank you very much ! had the same problem, I was entering the url of my site too...Miran
Glad to help. Could you mark this as the correct answer?Handal
I don't have Web Origin settings in my Keycloak client. Where do you find it?Ellynellynn
@GinoPane, you can find it after you select realm and select your client-id on clients menu sidebar, and search web origins.Ermey
just add * to "web origin" and then worked for me with localhostScarper
To add some information to this answer, maybe you need to add the client's URL in the Admin URL field at Client's Access settings configuration.Rotenone
H
10

I agree, that you need to configure Web Origins, but:

Holtz answered 25/11, 2019 at 23:2 Comment(4)
Thank you, I changed the host in the address bar to 127.0.0.1 instead of localhost, added this IP (+ relevant port) to Web Origins and CORS magically started woking!Cryptanalysis
so don't use localhost for development - this gave me laughMeunier
@ParamvirSinghKarwal good luck with your laugh on localhost and chrome and authenticated requestsHoltz
joke's on chrome! :)Meunier
T
5

For CORS related issue you have to set Web Origins. Below is the official documentation

Web Origins

This option centers around CORS which stands for Cross-Origin Resource Sharing. If browser JavaScript tries to make an AJAX HTTP request to a server whose domain is different from the one the JavaScript code came from, then the request must use CORS. The server must handle CORS requests in a special way, otherwise the browser will not display or allow the request to be processed. This protocol exists to protect against XSS, CSRF and other JavaScript-based attacks.

Keycloak has support for validated CORS requests. The way it works is that the domains listed in the Web Origins setting for the client are embedded within the access token sent to the client application. The client application can then use this information to decide whether or not to allow a CORS request to be invoked on it. This is an extension to the OIDC protocol so only Keycloak client adapters support this feature. See Securing Applications and Services Guide for more information.

To fill in the Web Origins data, enter in a base URL and click the + sign to add. Click the - sign next to URLs you want to remove. Remember that you still have to click the Save button!

So in your client set 'Web Origins' (or just add * ).

Training answered 25/11, 2019 at 6:2 Comment(3)
Thank you for your help! :) The "*" works but I wanted to use my URI, and thanks to Robin, I made it!Miran
When adding * to Web Origins, you are basically disabling security on your Keycloak server. It allows any script from any domain to make requests on behalf of a user, within that user's browser.Robert
Adding * to "web origin" worked for me with localhost, many thanksScarper
C
2

It may be a little late for some. but in my case the problem was that the keycloak URL was not correctly written in my fronted. make sure you have the next structure in your provider or issuer: http://server_ip:PORT/auth/realms/realm_name

Carleton answered 15/2, 2022 at 23:47 Comment(0)
R
-1

I agree, that you need to configure Web Origins, but maybe, you have to configure Wildfly to provide CORS support.

Here is sample config (standalone.xml) :

<subsystem xmlns="urn:jboss:domain:undertow:12.0" default-server="default-server" default-virtual-host="default-host" default-servlet-container="default" default-security-domain="other" statistics-enabled="${wildfly.undertow.statistics-enabled:${wildfly.statistics-enabled:false}}">
    <buffer-cache name="default"/>
    <server name="default-server">
        <http-listener name="default" socket-binding="http" redirect-socket="https"/>
        <host name="default-host" alias="localhost">
            <location name="/" handler="welcome-content"/>
            <filter-ref name="server-header"/>
            <filter-ref name="x-powered-by-header"/>
            <filter-ref name="Access-Control-Allow-Origin"/>
            <filter-ref name="Access-Control-Allow-Methods"/>
            <filter-ref name="Access-Control-Allow-Headers"/>
            <filter-ref name="Access-Control-Allow-Credentials"/>
            <filter-ref name="Access-Control-Max-Age"/>
        </host>
    </server>
    <servlet-container name="default">
        <jsp-config/>
        <websockets/>
    </servlet-container>
    <handlers>
        <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
    </handlers>
    <filters>
        <response-header name="server-header" header-name="Server" header-value="WildFly"/>
        <response-header name="x-powered-by-header" header-name="X-Powered-By" header-value="Undertow"/>
        <response-header name="Access-Control-Allow-Methods" header-name="Access-Control-Allow-Methods" header-value="GET, POST, OPTIONS, PUT"/>
        <response-header name="Access-Control-Allow-Headers" header-name="Access-Control-Allow-Headers" header-value="accept, authorization, content-type, x-requested-with, Access-Control-Allow-Origin"/>
        <response-header name="Access-Control-Max-Age" header-name="Access-Control-Max-Age" header-value="1"/>
    </filters>
</subsystem>
Remains answered 7/1, 2022 at 9:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.