在Angular中使用JWT令牌进行身份验证的一种常见方法是通过拦截器(interceptor)来处理每个请求。以下是一个基本的示例:
npm install jsonwebtoken
jwt.interceptor.ts
的新文件,并添加以下代码:import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) {}
intercept(request: HttpRequest, next: HttpHandler): Observable> {
// 添加JWT令牌到请求的头部
const currentUser = this.authService.getCurrentUser();
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
auth.service.ts
的新文件,并添加以下代码:import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class AuthService {
constructor(private http: HttpClient) {}
login(username: string, password: string) {
return this.http.post('/api/auth/login', { username, password });
}
getCurrentUser() {
// 从本地存储获取当前用户信息,包括JWT令牌
return JSON.parse(localStorage.getItem('currentUser'));
}
setCurrentUser(user: any) {
// 将当前用户信息保存到本地存储
localStorage.setItem('currentUser', JSON.stringify(user));
}
logout() {
// 从本地存储中移除当前用户信息
localStorage.removeItem('currentUser');
}
}
app.module.ts
文件中注册拦截器:import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { JwtInterceptor } from './jwt.interceptor';
@NgModule({
imports: [
HttpClientModule
],
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }
]
})
export class AppModule { }
现在,每个发出的HTTP请求都会由拦截器处理,它会在请求头中添加JWT令牌。你可以在AuthService
中的login
方法中获取JWT令牌,并将其保存在本地存储中。在其他需要进行身份验证的请求中,拦截器将自动添加JWT令牌到请求头中。
请注意,上述代码示例仅供参考,你可能需要根据你的实际需求进行调整。