0

I am trying to connect to Keyckloak to get the 'access_token' with angular. But I have this error :

Failed to load http://localhost:8080/auth/realms/demo/protocol/openid-connect/token: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 400.

I give you my code :

readonly ROOT_URL = 'http://localhost:8080/auth/realms/demo/protocol/openid-connect/token';
posts : any;    

constructor(private http: HttpClient) {}

getToken() {
const data: Post = {
username: 'pierrecolart',
password: 'root',
grant_type: 'password',
client_id: 'admin-cli'
}
this.http
    .post(
        this.ROOT_URL,
        data, 
        {headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')}
    )
    .map(res => res.json())
    .subscribe(data => console.log(data))
}
Pierre Colart
  • 165
  • 4
  • 15

2 Answers2

0

CORS access issue, you need to allow cors on your api server. Normally you will encounter this issue when your API and Front End is running on different domains 8080 and 4200 this is browser default security, but you actually failed to give information about your backend language

How to allow CORS? checkout this post for Nodejs, it should be helpful enough

  • So the problem comes from that I use 2 localhost ? – Pierre Colart Feb 25 '18 at 16:16
  • that's right, normally when you do this you only need slight configuration and it will work. What's backend language, and what type of API are you using SOAP or REST – Ezell Buoee Feb 25 '18 at 16:20
  • that works thank you but I have this error now : HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "http://localhost:8080/auth/realms/demo/protocol/openid-connect/token", ok: false, …} error : error : "invalid_request" error_description : "Missing form parameter: grant_type" __proto__ : Object headers : HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message : "Http failure response for http://localhost:8080/auth/realms/demo/protocol/openid-connect/token: 400 Bad Request" name : – Pierre Colart Feb 25 '18 at 16:27
-1

Assuming you are using express, you will have to allow CORS in the server file:

`var $app = express();
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    next();
};
$app.use(allowCrossDomain);`