gpt4 book ai didi

node.js - 如何在页面加载之前处理 token ?

转载 作者:太空宇宙 更新时间:2023-11-04 02:45:00 25 4
gpt4 key购买 nike

我使用 JWT 进行身份验证(没有登录页面)。我有一些问题,当网站加载时,首先启动的是加载内容的获取方法,然后是身份验证方法并将 token 保存在本地存储中。

问题是我收到错误消息,表明我未经过身份验证,并且在刷新页面后其工作正常。我需要让他首先制定身份验证方法并将其保存到本地存储,然后加载页面。

验证服务:

import { Injectable } from '@angular/core';
import { HttpService } from '../http/http.service';
import * as jwt_decode from 'jwt-decode';

@Injectable({
providedIn: 'root'
})
export class AuthService {
public isDialogOpen = false;

constructor(private http: HttpService) { }

authUser(userID) {
if (localStorage.getItem('token') === null) {
this.http.authUser(userID).subscribe((data) => {
localStorage.setItem('token', data.token);
}, error => {
console.log(error);
});
}
}

removeToken() {
localStorage.clear();
}

getCurrentUser() {
try {
const jwt = localStorage.getItem('token');
return jwt_decode(jwt);
} catch (error) {
return null;
}
}
}

header .拦截器:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../services/auth.service';

@Injectable()
export class HeaderInterceptor implements HttpInterceptor {
constructor(public authService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.token;
if (!token) {
return next.handle(request);
}

request = request.clone({
setHeaders: {
'Content-Type': 'application/json',
'x-auth-token': token
}
});
return next.handle(request);
}
}

Error.interceptor.ts:

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthService } from '../services/auth.service';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(public authService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(err => {
if (err) {
console.log(`Server Error`);
}
if (err.status === 401) {
this.authService.authUser('1');
}
const error = err.error.message || err.statusText;
return throwError(error);
})
);
}
}

最佳答案

您应该将代码分开。您的请求处理不应显式等待身份验证成功:相反,应全面使用可观察对象。

Auth0 help page 就是一个很好的例子来说明如何使用它。 。即使您不使用 Auth0 后端,该架构也是您所需要的:您的 auth 服务将 token 作为可观察对象返回,而您需要它的其他地方则订阅该可观察对象。

此外,you should not use localStorage to store your tokens或就此而言的 Cookie。相反,使用标准 OAuth 协议(protocol)检索它(Okta、Auth0 等专用服务或开源替代方案提供了可以处理此问题的 SDK)。

例如 Auth0 SDK :

Why isn't the token stored in browser storage? Historically, it was common to store tokens in local or session storage. However, browser storage is not a secure place to store sensitive data. The auth0-spa-js SDK manages session retrieval for you so that you no longer need to store sensitive data in browser storage in order to restore sessions after refreshing a Single Page Application.

With auth0-spa-js, we can simply request the token from the SDK when we need it (e.g., in an HTTP interceptor) rather than storing it locally in the Angular app or browser. The SDK manages token freshness as well, so we don't need to worry about renewing tokens when they expire.

注意:我不隶属于 Auth0,只是在我的最新项目中使用了该服务:)

关于node.js - 如何在页面加载之前处理 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58788061/

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