typescript - 使用 GraphQL 和 Apollo 客户端为 Angular 刷新令牌
我正在尝试在 Angular 9 中使用 GraphQL 和 Apollo 客户端设置刷新令牌策略,以在我的第一个请求返回 401 时刷新 JWT。
我已经为 GraphQL 设置了一个新的 Angular 模块,在那里我创建了我的 Apollo 客户端。即使是带身份验证的请求,一切都运行良好,但我还需要让我的普通刷新令牌策略正常工作(在刷新令牌周期完成后重新创建并返回原始请求)。我只找到了一些帮助资源,而且我已经非常接近了——唯一缺少的就是从我的刷新令牌 Observable 返回可观察对象。
这是我认为应该可行的代码:
import { NgModule } from '@angular/core';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { AuthenticationService } from './authentication/services/authentication.service';
import { ApolloLink } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { onError } from 'apollo-link-error';
export function createApollo(httpLink: HttpLink, authenticationService: AuthenticationService) {
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
Authorization: 'Bearer ' + localStorage.getItem('auth_token')
}
});
return forward(operation);
});
const errorLink = onError(({ forward, graphQLErrors, networkError, operation }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) =>
{
if (message.toLowerCase() === 'unauthorized') {
authenticationService.refreshToken().subscribe(() => {
return forward(operation);
});
}
}
);
}
});
return {
link: errorLink.concat(authLink.concat(httpLink.create({ uri: 'http://localhost:3000/graphql' }))),
cache: new InMemoryCache(),
};
}
@NgModule({
exports: [ApolloModule, HttpLinkModule],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink, AuthenticationService]
}
]
})
export class GraphqlModule { }
我知道我的请求第二次能够工作,因为如果我在 authenticationService 订阅中记录 forward(operation) 可观察对象的结果,我可以在最初的 401 失败之后看到结果。
if (message.toLowerCase() === 'unauthorized') {
authenticationService.refreshToken().subscribe(() => {
return forward(operation).subscribe(result => {
console.log(result);
});
});
}
上面向我显示了来自原始请求的数据,但它没有传递给最初调用 GraphQL 的组件。
我对可观察对象远非专家,但我在想我可能需要做某种映射(flatmap,mergemap 等)来让这个返回值正常工作,但我就是不知道。
任何帮助都将不胜感激
一过性脑缺血发作
编辑 #1:这让我更接近了,因为它现在实际上订阅了我在 AuthenticationService 中的方法(我在 tap() 中看到了结果)
const errorLink = onError(({ forward, graphQLErrors, networkError, operation }) => {
if (graphQLErrors) {
if (graphQLErrors[0].message.toLowerCase() === 'unauthorized') {
return authenticationService.refreshToken()
.pipe(
switchMap(() => forward(operation))
);
}
}
});
我现在看到抛出了这个错误:
core.js:6210 错误 TypeError:您提供了一个无效的对象,本应提供一个流。您可以提供一个 Observable、Promise、数组或可迭代对象。
编辑 #2:包括 onError() 函数签名的截图:
Edit #3 This is the final effective solution in case others encounter this problem and need it for Angular.我不喜欢必须更新我的服务方法来返回 Promise,然后将该 Promise 转换为 Observable,但正如 @Andrei Gătej 为我发现的那样,这个 Observable 来自不同的命名空间。
import { NgModule } from '@angular/core';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';
import { AuthenticationService } from './authentication/services/authentication.service';
import { ApolloLink } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloModule, APOLLO_OPTIONS } from 'apollo-angular';
import { onError } from 'apollo-link-error';
import { Observable } from 'apollo-link';
export function createApollo(httpLink: HttpLink, authenticationService: AuthenticationService) {
const authLink = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
Authorization: 'Bearer ' + localStorage.getItem('auth_token')
}
});
return forward(operation);
});
const errorLink = onError(({ forward, graphQLErrors, networkError, operation }) => {
if (graphQLErrors) {
if (graphQLErrors.some(x => x.message.toLowerCase() === 'unauthorized')) {
return promiseToObservable(authenticationService.refreshToken().toPromise()).flatMap(() => forward(operation));
}
}
});
return {
link: errorLink.concat(authLink.concat(httpLink.create({ uri: '/graphql' }))),
cache: new InMemoryCache(),
};
}
const promiseToObservable = (promise: Promise<any>) =>
new Observable((subscriber: any) => {
promise.then(
value => {
if (subscriber.closed) {
return;
}
subscriber.next(value);
subscriber.complete();
},
err => subscriber.error(err)
);
});
@NgModule({
exports: [ApolloModule, HttpLinkModule],
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink, AuthenticationService]
}
]
})
export class GraphqlModule { }
答案#1
这是我为将来看到这个的人实现的版本
GraphQL 模块:
import { NgModule } from '@angular/core';
import { APOLLO_OPTIONS } from 'apollo-angular';
import {
ApolloClientOptions,
InMemoryCache,
ApolloLink,
} from '@apollo/client/core';
import { HttpLink } from 'apollo-angular/http';
import { environment } from '../environments/environment';
import { UserService } from './shared/services/user.service';
import { onError } from '@apollo/client/link/error';
import { switchMap } from 'rxjs/operators';
const uri = environment.apiUrl;
let isRefreshToken = false;
let unHandledError = false;
export function createApollo(
httpLink: HttpLink,
userService: UserService
): ApolloClientOptions<any> {
const auth = new ApolloLink((operation, forward) => {
userService.user$.subscribe((res) => {
setTokenInHeader(operation);
isRefreshToken = false;
});
return forward(operation);
});
const errorHandler = onError(
({ forward, graphQLErrors, networkError, operation }): any => {
if (graphQLErrors && !unHandledError) {
if (
graphQLErrors.some((x) =>
x.message.toLowerCase().includes('unauthorized')
)
) {
isRefreshToken = true;
return userService
.refreshToken()
.pipe(switchMap((res) => forward(operation)));
} else {
userService.logOut('Other Error');
}
unHandledError = true;
} else {
unHandledError = false;
}
}
);
const link = ApolloLink.from([errorHandler, auth, httpLink.create({ uri })]);
return {
link,
cache: new InMemoryCache(),
connectToDevTools: !environment.production,
};
}
function setTokenInHeader(operation) {
const tokenKey = isRefreshToken ? 'refreshToken' : 'token';
const token = localStorage.getItem(tokenKey) || '';
operation.setContext({
headers: {
token,
Accept: 'charset=utf-8',
},
});
}
@NgModule({
providers: [
{
provide: APOLLO_OPTIONS,
useFactory: createApollo,
deps: [HttpLink, UserService],
},
],
})
export class GraphQLModule {}
用户服务/认证服务:
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { User, RefreshTokenGQL } from '../../../generated/graphql';
import jwt_decode from 'jwt-decode';
import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, tap } from 'rxjs/operators';
import { AlertService } from './alert.service';
@Injectable({
providedIn: 'root',
})
export class UserService {
private userSubject: BehaviorSubject<User>;
public user$: Observable<User>;
constructor(
private router: Router,
private injector: Injector,
private alert: AlertService
) {
const token = localStorage.getItem('token');
let user;
if (token && token !== 'undefined') {
try {
user = jwt_decode(token);
} catch (error) {
console.log('error', error);
}
}
this.userSubject = new BehaviorSubject<User>(user);
this.user$ = this.userSubject.asObservable();
}
setToken(token?: string, refreshToken?: string) {
let user;
if (token) {
user = jwt_decode(token);
localStorage.setItem('token', token);
localStorage.setItem('refreshToken', refreshToken);
} else {
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
}
this.userSubject.next(user);
return user;
}
logOut(msg?: string) {
if (msg) {
this.alert.addInfo('Logging out...', msg);
}
this.setToken();
this.router.navigateByUrl('/auth/login');
}
getUser() {
return this.userSubject.value;
}
refreshToken() {
const refreshTokenMutation = this.injector.get<RefreshTokenGQL>(
RefreshTokenGQL
);
return refreshTokenMutation.mutate().pipe(
tap(({ data: { refreshToken: res } }) => {
this.setToken(res.token, res.refreshToken);
}),
catchError((error) => {
console.log('On Refresh Error: ', error);
this.logOut('Session Expired, Log-in again');
return throwError('Session Expired, Log-in again');
})
);
}
}
答案#2
我对 GraphQL 不太熟悉,但我认为这应该可以正常工作:
if (message.toLowerCase() === 'unauthorized') {
return authenticationService.refreshToken()
.pipe(
switchMap(() => forward(operation))
);
}
另外,如果你想了解 mergeMap(和 concatMap)是如何工作的,你可以看看这个答案。
switchMap 只保持一个活跃的内部可观察对象,一旦有外部值到来,当前的内部可观察对象将被取消订阅,并基于新到的外部值和提供的函数创建一个新的内部可观察对象。
