我想从用Django编写的后端服务器(JWT令牌)登录token
的页面,根据这个login router
,我终于在angular-7-jwt-authentication-example-tutorial获得了200,但登录后,我不知道如何携带此令牌并访问其他页面,添加currentUser
来识别或导入一些文件?真的陷入了这个问题。任何建议将受到高度赞赏。
src/services/auth.service.ts
的部分代码如下:
import { Inject, Injectable } from '@angular/core';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { Auth, User } from '../domain';
import { map, switchMap } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class AuthService {
private currentUserSubject: BehaviorSubject<Auth>;
public currentUser: Observable<Auth>;
constructor(
private http: HttpClient,
@Inject('BASE_CONFIG') private config: { uri: string }
) {
this.currentUserSubject = new BehaviorSubject<Auth>(JSON.parse(localStorage.getItem('currentUser') || '{}'));
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): Auth {
return this.currentUserSubject.value;
}
login(email: string, password: string): Observable<Auth> {
return this.http.post<any>(`${this.config.uri}/users`, { email, password })
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
return user;
}));
}
src/services/project.service.ts
的部分代码如下:
// GET /projects
@Injectable({ providedIn: 'root' })
export class ProjectService {
private readonly domain = 'projects';
private headers = new HttpHeaders().set('Authorization', '`Beader ${jwt}`');
get(username: string): Observable<Project[]> {
const uri = `${this.config.uri}/projects`;
// const uri = `${this.config.uri}/project/`;
const params = new HttpParams().set('members_like', username);
return this.http.get<Project[]>(uri, {
params: params,
headers: this.headers
});
}
src/helper/jwt.interceptor.ts
的部分代码如下:
import { AuthService } from '../services/auth.service';
// import { Router } from '@angular/router';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// add authorization header with jwt token if available
let currentUser = this.authService.currentUserValue;
if (currentUser && currentUser.token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${currentUser.token}`
}
});
}
return next.handle(request);
}
}
在发出请求的服务中,您需要将Authorization
标头设置为值Bearer <your_token>
这是在JWT中进行身份验证的标准方法。然后,服务器将验证此令牌(签名,受众,日期到期...),如果有效,将在有效负载中选择用户身份。
const headers = new HttpHeaders();
const options = {};
headers.set("Authorization", `Beader ${jwt}`";
options = { headers };
http.get<T>(path, body, options);
http
指的是来自HttpClient
的@angular/common/http
基本上你应该遵循这个流程:
要注销用户: