As I work on implementing SSO login in my code, I encounter a recurring issue. Within my app.module.ts
, there is an auth.service
provided inside an app initializer
. Upon hitting the necessary service and capturing the code from the URL, I proceed to send a POST request containing a body
that should return the access token. However, upon making the post request, the application refreshes and the process repeats itself. After several attempts, it terminates with a message stating that the Authorization code has expired
.
export function appsso(http: HttpClient, authService: AuthService) {
return (): Promise<any> => {
return authService.init()
};
}
{provide: APP_INITIALIZER, useFactory: appsso, deps: [HttpClient, AuthService], multi: true}
Inside authService file:
constructor(private http: HttpClient) {}
init() {
return new Promise<void>((resolve, reject) => {
console.log('init is called');
if (localStorage.getItem('token')) {
console.log('good to go');
} else {
if (!location.href.includes('?code=')) {
const params = [
'response_type=code',
'client_id=abcde',
'scope=openid profile',
'redirect_uri=https://URLhere/a.0/',
];
location.href = 'https://secureURLhere/authorize?' + params.join('&');
return
} else {
const code = window.location.href.split('=')[1];
return this.getAuthToken(code).then(data): any => {
localStorage.setItem('tokenData', data);
console.log('access token received');
resolve();
}, error ((err) => {
console.log ('error occured');
reject();
});
}
}
}
getAuthToken(code: string){
let body: HttpParams = new HttpParams();
body = body.append('grant_type', 'authorization_code')
body = body.append('code', code)
body = body.append('client_id', 'abcde')
body = body.append('client_secret', '12345');
return this.http.post('https://secureURLhere/token', body).toPromise();
}
Additionally, the header
is set to
'Content-Type': 'application/x-www-form-urlencoded'
. Despite setting up for receiving the access token when the Post API is hit, the application continues to refresh. How can this persistent issue be resolved?