I am implementing the authorization code flow with Nestjs and keycloak, I have already redirected the login request to the keycloak login page, I received the authorization code and when making the post to the callback url, I get the following error:
Converting circular structure to JSON
-> starting at object with constructor 'ClientRequest'
| property 'socket' -> object with constructor 'Socket'
--- property '_httpMessage' closes the circle
I noticed that this error happens only after passing the authorization code as a parameter:
follow the code:
import { HttpException, HttpService, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { KeycloakConnectModule } from 'nest-keycloak-connect';
import * as queryString from 'querystring'
import { catchError } from 'rxjs/operators';
@Injectable()
export class AuthService {
private keycloakLoginUri: string;
private keycloakResponseType: string;
private keycloakScope: string;
private keycloakRedirectUri: string;
private keycloakGrantType: string;
private keycloakClientId: string;
private keycloakClientSecret: string;
private keycloakTokenUri: string;
constructor( readonly _config: ConfigService, private readonly _http: HttpService) {
this.keycloakLoginUri = _config.get('KEYCLOAK_LOGIN_URI');
this.keycloakResponseType = _config.get('KEYCLOAK_RESPONSE_TYPE');
this.keycloakScope = _config.get('KEYCLOAK_SCOPE');
this.keycloakRedirectUri = _config.get('KEYCLOAK_REDIRECT_URI');
this.keycloakGrantType = 'authorization_code';
this.keycloakClientId = _config.get('KEYCLOAK_CLIENT_ID');
this.keycloakClientSecret = _config.get('KEYCLOAK_CLIENT_SECRET');
this.keycloakTokenUri = this._config.get('KEYCLOAK_TOKEN_URI');
}
getLoginUrl(): any {
return { url: `${this.keycloakLoginUri}`
+`?client_id=${this.keycloakClientId}`
+`&response_type=${this.keycloakResponseType}`
+`&scope=${this.keycloakScope}`
+`&redirect_uri=${this.keycloakRedirectUri}`
}
}
getKeyCloakToken(code: string){
const params = {
grant_type: this.keycloakGrantType,
client_id: this.keycloakClientId,
client_secret: this.keycloakClientSecret,
code: code,
redirect_uri: this.keycloakRedirectUri
};
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
return this._http.post(
this.keycloakTokenUri,
queryString.stringify(params),
config)
.pipe(catchError(e => {
throw new HttpException(e.response.data, e.response.status);
}));
}
}
Enviroments variables defined on .env:
KEYCLOAK_LOGIN_URI=http://localhost:8080/auth/realms/onboarding-arqt/protocol/openid-connect/auth
KEYCLOAK_AUTH_URI=http://localhost:8080/auth
KEYCLOAK_TOKEN_URI=http://localhost:8080/auth/realms/onboarding-arqt/protocol/openid-connect/token?
KEYCLOAK_GRANT_TYPE=authorization_code
KEYCLOAK_REALM=my-realm
KEYCLOAK_CLIENT_ID=my-id
KEYCLOAK_CLIENT_SECRET=my-secret
KEYCLOAK_REDIRECT_URI=http://localhost:3000/callback
KEYCLOAK_SCOPE=profile
KEYCLOAK_RESPONSE_TYPE=code