How to setup the CORS configuration in keycloak to allow an ajax request?

房东的猫 提交于 2019-12-29 08:15:34

问题


I am trying to use keycloak as an authentication server. I try to get the token with an ajax request. It works fine in curl but not in my angular due to CORS. I have set the client to Direct access grant enable to true and I have added * to Web Origin.

fetch("http://localhost:8080/auth/realms/master/protocol/openid-connect/token", {
  body: "grant_type=password&client_id=admin-cli&username=adrien&password=adrien&undefined=",
  headers: {
    Accept: "application/json, text/plain, */*,application/x-www-form-urlencoded",
    "Access-Control-Allow-Headers": "Origin, Content-Type, Authorization, Content-Length, X-Requested-With",
    "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,OPTIONS",
    "Access-Control-Allow-Origin": "*",
    "Cache-Control": "no-cache",
    "Content-Type": "application/x-www-form-urlencoded",
    Dnt: "1",
    "Postman-Token": "cfd33776-882d-4850-b2e7-d66629da3826"
  },
  method: "POST"
})

Do you know what I am missing?

Thanks in advance.


回答1:


I think you are trying it to use it in the wrong way. There is plugin for angular and i think you should use it. So here are the clifnotes. Install the plugin:

npm i keycloak-angular

then initialize the keycloack:

import {KeycloakService} from 'keycloak-angular';

export function initializer(keycloak: KeycloakService): () => Promise<any> {
  return (): Promise<any> => {
    return new Promise(async (resolve, reject) => {
      try {
        await keycloak.init({
          config: {
            url: 'http://localhost:8080/auth',
            realm: 'MySecureRealm',
            clientId: 'myAngularApplication'
          },
          initOptions: {
            onLoad: 'login-required',
            checkLoginIframe: false,
            responseMode: 'fragment',
            flow: 'standard'
          }
        });
        resolve();
      } catch (error) {
        reject(error);
      }
    });
  };
}

and then in app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import {APP_INITIALIZER, NgModule} from '@angular/core';


import { AppComponent } from './app.component';
import {KeycloakService} from 'keycloak-angular';
import {initializer} from '../environments/environment';
import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
import {TokenInterceptor} from './token-interceptor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    KeycloakService,
    {
      provide: APP_INITIALIZER,
      useFactory: initializer,
      multi: true,
      deps: [KeycloakService]
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    },
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

you will also need this TokenInterceptor:

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/observable/fromPromise';

import { KeycloakService, KeycloakAuthGuard, KeycloakAngularModule } from 'keycloak-angular';
import {HttpHeaders} from '@angular/common/http/src/headers';

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(protected keycloak: KeycloakService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return Observable
      .fromPromise(this.keycloak.getToken())
      .mergeMap(
      token => {

        console.log('adding heder to request');
        console.log(token);

        const headers: HttpHeaders = req.headers;
        const hedersWithAuthorization: HttpHeaders = headers.append('Authorization', 'bearer ' + token);
        const requestWithAuthorizationHeader = req.clone({ headers: hedersWithAuthorization });
        return next.handle(requestWithAuthorizationHeader);
      }
    );
  }
}

And that should do it. When you enter application and you are not logged in you will be redirected to the keycloak login screen and the back to your app. And to all outgoing request will be added the authentication header. Let me know if you have nay trouble I know the technology quite well.



来源:https://stackoverflow.com/questions/53997701/how-to-setup-the-cors-configuration-in-keycloak-to-allow-an-ajax-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!