gpt4 book ai didi

angular - 使用 graphql 和 apollo 客户端刷新 Angular 的 token

转载 作者:行者123 更新时间:2023-12-02 02:52:41 28 4
gpt4 key购买 nike

当我的第一个请求返回 401 时,我正在尝试设置刷新 token 策略,以使用 GraphQL 和 apollo 客户端刷新 Angular 9 中的 JWT。

我已经为 graphql 设置了一个新的 Angular 模块,我正在其中创建我的 apolloclient。即使对于经过身份验证的请求,一切都很好,但我也需要正常的刷新 token 策略也能工作(刷新 token 周期完成后重新发出并返回原始请求)。我只找到了一些资源来帮助解决这个问题,而且我已经非常接近了 - 我唯一缺少的是从我的刷新 token observable 返回 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(操作)中注销结果,我可以在最初的401失败后看到结果。

 if (message.toLowerCase() === 'unauthorized') {
authenticationService.refreshToken().subscribe(() => {
return forward(operation).subscribe(result => {
console.log(result);
});
});
}

上面显示了原始请求中的数据,但它没有传递到最初调用 graphql 的组件。

我远不是可观察的专家,但我想我需要做某种 map (平面 map 、合并 map 等)才能使此返回正常工作,但我只是不知道。

任何帮助将不胜感激

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() 函数签名的屏幕截图: enter image description here

编辑 #3 这是最终的工作解决方案,以防其他人遇到此问题并需要它进行 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 { }

最佳答案

这是我的实现,供将来看到此内容的人使用

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 {}

用户服务/验证服务:

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');
})
);
}
}


关于angular - 使用 graphql 和 apollo 客户端刷新 Angular 的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61698472/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com