I am building an SPA with Angular 5 and I'm calling an authentication and authorization service. This service checks if I have a session active and if there's no session or if it has expired then returns 401 and an HTML with the company-wide login page. I built a service for making this call, like this:
@Injectable()
export class AuthService {
private authServicePath = '/<path-to-the-service>';
private authToken: string;
private serviceURL: string;
private requestOptions: any;
constructor(private http: HttpClient, private cookieService: CookieService) { }
validateAuth() {
this.serviceURL = environment.endpoint + this.authServicePath;
this.authToken = this.cookieService.get('SESSION-TOKEN-COOKIE');
this.requestOptions = {
headers: new HttpHeaders(
{
'SESSION-TOKEN-COOKIE': this.authToken
}
)
};
return this
.http
.get(this.serviceURL, this.requestOptions)
.subscribe(
data => {
// Do nothing
},
(err: HttpErrorResponse) => {
/*window.document.write = err.error;
window.document.close();*/
}
);
}
}
As you can see, I'm calling the service. If the token is valid then there's nothing to do, but if I don't have any active/valid session, then the service will return the 401 Unauthorized and in its payload (.error
field) I will get something like this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<form action="..." ...
How do I tell my app to redirect me to this generated page?
As you can see, I tried writing a new HTML with window.document.write
but it didn't work.
I understand that Angular Router can only redirect to components belonging to the app.
Thanks in advance.
Ok, so, I found a way to do this. It looks very hackish to me, but it is the first step. If someone has any advice on this, please let me know.
I used Javascript the old way to append the content of the generated HTML to the <body>
tag of my app. Since the HTML contains an unnamed form, I've done this:
(err: HttpErrorResponse) => {
if (err.status === 401){
document.body.innerHTML = err.error;
let form = <HTMLFormElement>document.getElementsByTagName('form')[0];
form.submit();
}
}
It looks ugly to me, but it is the best that I can get at this time. If someone has another approach to this, please let me know. I'll mark this question as answered and if there is a better answer I'll be happy to mark it as the right answer.
Thanks