我正在嘗試使用 JWT 對用戶進行身份驗證。我在登錄時分配一個令牌。
if (client) {
// Check if Client does exist, then compare password provided by Client
if (!req.body.password) {
res.json({ success: false, message: "No password provided" }); // Password was not provided
} else {
var validPassword = client.password === req.body.password; // Check if password matches password provided by Client
if (!validPassword) {
res.json({ success: false, message: {password: {message: "Incorrect Password"}} }); // Password does not match password in database
} else {
if (!client.active) {
res.json({ success: false, message: {active: {message: "Account is not activated"}} }); // Account is not activated
} else {
var token = jwt.sign(
{ username: client.username, email: client.email },
secret,
{ expiresIn: "24h" }
); // Logged in: Give Client token
res.json({
success: true,
message: "Client authenticated!",
token: token
}); // Return token in JSON object to controller
}
}
}
}
登錄后,我正在檢查作為我的用戶的請求中的令牌。
router.use(function(req, res, next) {
var token = req.body.token || req.body.query || req.headers['x-access-token']; // Check for token in body, URL, or headers
// Check if token is valid and not expired
if (token) {
// Function to verify token
jwt.verify(token, secret, (err, decoded) => {
if (err) {
res.json({ success: false, message: 'Token invalid' }); // Token has expired or is invalid
} else {
req.decoded = decoded; // Assign to req. variable to be able to use it in next() route ('/me' route)
next(); // Required to leave middleware
}
});
} else {
res.json({ success: false, message: 'No token provided' }); // Return error if no token was provided in the request
}
});
我將所有受保護的路由放在檢查令牌之后。用戶可以訪問個人資料頁面 /me
router.post('/me', function(req, res) {
res.send(req.decoded); // Return the token acquired from middleware
});
如何在 Angular 11 中檢查 req.body 中的令牌?我曾嘗試使用 localStorage 設定令牌,但似乎我沒有正確執行。
localStorage.setItem('userToken', response.token);
通過在正文中傳遞令牌訪問 /me 路由時,它似乎在 Postman 中作業正常。它顯示是否找到令牌。如果找到,則顯示結果
{ "email": "[email protected]", "iat": 1634704834, "exp": 1634791234 }
uj5u.com熱心網友回復:
一切似乎都很好。我認為,你只需要在前端實作一個攔截器。它將從本地存盤中選擇身份驗證令牌,并將其與所有請求附加在一起。
示例代碼
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './service/auth.module';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let loggedInUser = this.authService.currentUserValue;
token = JSON.parse(localStorage.getItem(user.token));
if (token) {
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`
}
});
}
return next.handle(request);
}
}
是的,在正文引數中發送身份驗證令牌不是一個好習慣。安全的方法是始終對此類敏感資訊使用標頭。可以在此處找到更多詳細資訊
uj5u.com熱心網友回復:
我使用了 HttpInterceptor
import { Injectable, Injector } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';
import { AuthService } from './auth.service';
@Injectable()
export class TokenInterceptorService implements HttpInterceptor {
constructor(private injector: Injector) {}
intercept(req, next) {
let auth = this.injector.get(AuthService);
let tokenizedReq = req.clone({
setHeaders: {
Authorization: `Bearer ${auth.getToken()}`,
},
});
return next.handle(tokenizedReq);
}
}
它反映了標頭中的令牌,但當我嘗試從任何路由上的后端獲取資料時提示“令牌無效”。我正在檢查 usingconsole.log(response);而它在 nodemon 中作業正常,同時在標頭中傳遞令牌。
請協助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/328290.html
