我正在尝试在HTTP调用中实现以下目标
- 如果API请求返回401,则调用刷新令牌端点以获取令牌
- 使用更新的令牌重试相同的HTTP调用
这是相关代码
// this method invoke when the HTTP interceptor returns 401 status code
handle401(request: HttpRequest<any>, next: HttpHandler) {
if (!this.refreshTokenInProgress) {
this.refreshTokenInProgress = true;
this.refreshTokenSubject.next(null);
return this.getToken((data: any) => {
this.refreshTokenInProgress = false;
this.refreshTokenSubject.next(data);
request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${data}`) });
return next.handle(request);
})
} else {
return this.refreshTokenSubject.pipe(
filter(token => token != null),
take(1),
switchMap((accessToken) => {
request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${accessToken}`) });
return next.handle(request);
})
);
}
}
获取刷新令牌
getToken(cb: any) {
let poolData = {
UserPoolId: environment.cognitoUserPoolId, // Your user pool id here
ClientId: environment.cognitoAppClientId // Your client id here
};
let userPool = new CognitoUserPool(poolData);
let cognitoUser = userPool.getCurrentUser();
cognitoUser?.getSession((err: any, session: any) => {
const refresh_token = session.getRefreshToken();
cognitoUser?.refreshSession(refresh_token, (refErr, refSession) => {
const userToken = localStorage.getItem('token');
cb(userToken);
});
})
}
在执行时,我从getToken
方法获得了新的令牌,但没有重试相同的HTTP调用。
在从getToken
方法获得刷新令牌之后,HTTP请求的执行停止。
有人能在这个问题上帮忙吗
如果使用catchError,则应返回Observable
您的getToken函数没有返回
也许你可以看这个
https://stackoverflow.com/a/73364684/19768317
假设您想从getToken()
获得userToken
。getToken()
应该返回一些东西,现在它没有返回任何东西。如果像getSession
或refreshSession
这样的一些方法是异步方法,那么这些方法也应该等待。
async handle401(request: HttpRequest<any>, next: HttpHandler) {
if (!this.refreshTokenInProgress) {
this.refreshTokenInProgress = true;
this.refreshTokenSubject.next(null);
const token = await this.getToken(); // put "cb" param here, wait for returned token, then continiue
this.refreshTokenInProgress = false;
this.refreshTokenSubject.next(token);
request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${token}`) });
return next.handle(request);
} else {
return this.refreshTokenSubject.pipe(
filter(token => token != null),
take(1),
switchMap((accessToken) => {
request = request.clone({ headers: request.headers.set('Authorization', `Bearer ${accessToken}`) });
return next.handle(request);
})
);
}
}
getToken(cb: any) {
let poolData = {
UserPoolId: environment.cognitoUserPoolId, // Your user pool id here
ClientId: environment.cognitoAppClientId // Your client id here
};
let userPool = new CognitoUserPool(poolData);
let cognitoUser = userPool.getCurrentUser();
cognitoUser?.getSession((err: any, session: any) => {
const refresh_token = session.getRefreshToken();
cognitoUser?.refreshSession(refresh_token, (refErr, refSession) => {
const userToken = localStorage.getItem('token');
cb(userToken);
return userToken;
});
})
}