Reputation: 2522
I am building an Angular application that requires authentication. This is accomplished through tokens. The tokens have a short lifespan and need to be regularly refreshed. I have referenced this question , but I feel my needs and code structure are distinct (for example, I am not looking to "hold" the class and I have separate interceptors).
The primary purpose of one interceptor is to add the token to the header:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
const authToken = this.authService.getToken();
const refreshToken = this.authService.getRefreshToken();
// If refresh token is expired, the user will need to relogin
if(refreshToken == null || this.authService.checkTokenExpired(true)) {
this.authService.logout();
return next.handle(req);
}
// There is no token to send, continue.
if (authToken == null || this.authService.checkTokenExpired()) {
return next.handle(req);
}
const authReq = req.clone({ setHeaders: { Authorization: "Bearer " + authToken } });
return next.handle(authReq);
}
}
I have a separate interceptor to handle the "401" error:
@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
const cBack = tap(res => {
console.log("Refreshed");
console.log("Token is " + this.authService.getToken());
next.handle(req.clone
({ setHeaders: { Authorization: "Bearer " + this.authService.getToken() } }));
})
return next.handle(req)
.catch((err: HttpErrorResponse) => {
if (err.status == 401) {
this.authService.refresh()
.pipe(cBack).subscribe();
}
console.log(err);
return _throw(err.message);
});
};
}
Where AuthService is the following:
@Injectable()
export class AuthService {
private authURL: string = "http://localhost:8090/oauth/token";
private loginPath : string = "/login";
isLoggedIn: boolean = false;
redirectURL: string;
constructor(private http: HttpClient) {
this.redirectURL = "";
this.isLoggedIn = this.getToken() != null;
}
login(user: string, password: string): Observable<boolean> {
var data = new FormData();
data.append("grant_type", "password");
data.append("username", user);
data.append("password ", password);
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Basic ' + window.btoa("web:secret")
})
};
return this.http.post<AuthResponseModel>(this.authURL, data, httpOptions)
.pipe(
map((r: AuthResponseModel) => {
if (r.access_token) {
localStorage.setItem("access_token", r.access_token);
localStorage.setItem("refresh_token", r.refresh_token);
this.isLoggedIn = true;
return true;
}
}
));
};
refresh() : Observable<boolean> {
var data = new FormData();
data.append("grant_type", "refresh_token");
data.append("refresh_token", this.getRefreshToken());
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Basic ' + window.btoa("web:secret")
})
};
return this.http.post<AuthResponseModel>(this.authURL, data, httpOptions)
.pipe(
map( r => {
localStorage.setItem("access_token", r.access_token);
localStorage.setItem("refresh_token", r.refresh_token);
this.isLoggedIn = true;
return true;
})
)
}
logout(): void {
localStorage.removeItem("access_token");
localStorage.removeItem("refresh_token");
this.isLoggedIn = false;
}
checkTokenExpired(checkRefresh = false) : boolean {
if(checkRefresh) { return decode(this.getRefreshToken()).exp < (Date.now().valueOf() / 1000); }
return decode(this.getToken()).exp < (Date.now().valueOf() / 1000);
}
getToken(): string {
return localStorage.getItem("access_token");
}
getRefreshToken() : string {
return localStorage.getItem('refresh_token');
}
}
When the application receives a 401, it does properly send a request to refresh the token. I get the "Refreshed" and "Token is ..." console.log
messages from the logging interceptor. Additionally, it does place the token in local storage as it should. If I manually refresh the page, it actually works. However, my end goal is, when the application receives a 401, to refresh the token, and the resend the original request. The last step is the behavior that is not currently functioning.
I would appreciate any help. Thanks.
EDIT:
Version with retryWhen.
let interceptor = this;
return next.handle(req.clone({ setHeaders: { Authorization: "Bearer " + this.authService.getToken() } }))
.pipe(
retryWhen(error$ => {
return error$.pipe(
mergeMap(error => {
if (error.status === 401) {
return interceptor.authService.refresh();
} else {
// re-throw
_throw(error)
}
})
);
})
);
Upvotes: 0
Views: 142
Reputation: 301
Not really sure why you need a Auth and Logging interceptor, but I think you can do something like this:
class Interceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next
.handle(req)
.pipe(
retryWhen(error$ => {
return error$.pipe(
mergeMap(error => {
if (error.status === 401) {
// fetch new token + retry
return this.someService.refreshToken();
} else {
// re-throw
_throw(error)
}
})
);
})
);
}
Upvotes: 1