angular - Angular 7登录后如何携带令牌并访问其他页面?- JWT 认证示例
问题描述
我想token
从用 Django 编写的后端服务器(JWT 令牌)登录页面,我终于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
基本上你应该遵循这个流程:
- 用用户凭证交换令牌
- 将用户令牌存储在 SessionStorage 中或作为 Cookie。我更喜欢 SessionStorage,因为用户可能有块 cookie。
- 在需要发送 HTTP 请求的每个服务中,检索此令牌并将其作为 Authorization 标头发送
注销用户:
- 使用令牌向注销端点发送请求到后端。
- 从 SessionStorage/Cookie 中删除令牌
推荐阅读
- javascript - 从外部文件获取 Javascript 值
- javascript - Redux.js , Webpack.js , index.html - 我的 redux 渲染函数没有更新 index.html DOM
- javascript - TextTrackList onchange 事件在 IE 和 Edge 中不起作用
- javascript - nodejs 导出的变量在第二次命中时不可重用
- reactjs - 试图将值传递给处理程序但接收为未定义
- c++ - 在 GLSL 中优化光线追踪着色器
- java - 使用 java 以编程方式启动 bash shell 命令“osascript”
- php - 在 PHP 中使用正则表达式批量重命名
- c# - 清空列表框的文本框时自动计算文本框的值为零
- text - 如何使用 bash/shell 更改特定的列内容字符串?