使用 graphql 和 apollo 客户端刷新 angular 的令牌
refresh token for angular using graphql and apollo client
我正在尝试设置一个刷新令牌策略,以便在我的第一个请求 returns a 401 时使用 GraphQL 和 apollo 客户端在 angular 9 中刷新 JWT。
我在创建 apolloclient 的地方为 graphql 设置了一个新的 angular 模块。即使使用经过身份验证的请求,一切都很好,但我也需要让我的正常刷新令牌策略工作(在刷新令牌周期完成后重新制作和 return 原始请求)。我只找到了一些资源来帮助解决这个问题,而且我已经非常接近了——我唯一缺少的是 return 从我的刷新令牌可观察到的可观察。
这是认为应该有效的代码:
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) observable 注销结果,我可以在最初的 401 失败后看到结果。
if (message.toLowerCase() === 'unauthorized') {
authenticationService.refreshToken().subscribe(() => {
return forward(operation).subscribe(result => {
console.log(result);
});
});
}
上面显示了原始请求的数据,但它没有传递到我最初调用 graphql 的组件。
我远不是 observables 的专家,但我想我需要做一些地图(平面图、合并图等)来使这个 return 正常工作,但我就是不这样做知道了。
如有任何帮助,我们将不胜感激
TIA
编辑#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 ERROR TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
编辑 #2:包括 onError() 函数签名的屏幕截图:
编辑 #3 这是最终的工作解决方案,以防其他人遇到此问题并需要它 angular。我不喜欢必须将我的服务方法更新为 return 一个承诺,然后将该承诺转换为一个 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 { }
我不太熟悉 GraphQL,但我认为这应该可以正常工作:
if (message.toLowerCase() === 'unauthorized') {
return authenticationService.refreshToken()
.pipe(
switchMap(() => forward(operation))
);
}
此外,如果您想了解 mergeMap
(和 concatMap
)的工作原理,可以查看 this answer.
switchMap
只保留一个活跃的内部可观察对象,一旦外部值进来,当前的内部可观察对象将被取消订阅,并根据新到达的外部值和提供的功能。
这是我的实现,以供将来看到此内容的任何人使用
Garaphql 模块:
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 {}
UserService/AuthService:
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');
})
);
}
}
我正在尝试设置一个刷新令牌策略,以便在我的第一个请求 returns a 401 时使用 GraphQL 和 apollo 客户端在 angular 9 中刷新 JWT。
我在创建 apolloclient 的地方为 graphql 设置了一个新的 angular 模块。即使使用经过身份验证的请求,一切都很好,但我也需要让我的正常刷新令牌策略工作(在刷新令牌周期完成后重新制作和 return 原始请求)。我只找到了一些资源来帮助解决这个问题,而且我已经非常接近了——我唯一缺少的是 return 从我的刷新令牌可观察到的可观察。
这是认为应该有效的代码:
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) observable 注销结果,我可以在最初的 401 失败后看到结果。
if (message.toLowerCase() === 'unauthorized') {
authenticationService.refreshToken().subscribe(() => {
return forward(operation).subscribe(result => {
console.log(result);
});
});
}
上面显示了原始请求的数据,但它没有传递到我最初调用 graphql 的组件。
我远不是 observables 的专家,但我想我需要做一些地图(平面图、合并图等)来使这个 return 正常工作,但我就是不这样做知道了。
如有任何帮助,我们将不胜感激
TIA
编辑#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 ERROR TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.
编辑 #2:包括 onError() 函数签名的屏幕截图:
编辑 #3 这是最终的工作解决方案,以防其他人遇到此问题并需要它 angular。我不喜欢必须将我的服务方法更新为 return 一个承诺,然后将该承诺转换为一个 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 { }
我不太熟悉 GraphQL,但我认为这应该可以正常工作:
if (message.toLowerCase() === 'unauthorized') {
return authenticationService.refreshToken()
.pipe(
switchMap(() => forward(operation))
);
}
此外,如果您想了解 mergeMap
(和 concatMap
)的工作原理,可以查看 this answer.
switchMap
只保留一个活跃的内部可观察对象,一旦外部值进来,当前的内部可观察对象将被取消订阅,并根据新到达的外部值和提供的功能。
这是我的实现,以供将来看到此内容的任何人使用
Garaphql 模块:
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 {}
UserService/AuthService:
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');
})
);
}
}