gpt4 book ai didi

node.js - 在 Angular 6 + Node js 中使用 token 的身份验证问题

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

我尝试使用 Node js 作为我的服务器以 Angular 构建一个身份验证功能,我对从 Angular 发送的 token 的识别有疑问。我使用 Angular HttpInterceptor 服务来处理 header ,并在我的 Node js 中创建了一个中间件函数。我收到的错误是:

{headers: HttpHeaders, status: 401, statusText: "Unauthorized"..

任何帮助将不胜感激

中间件功能

const jwt = require("jsonwebtoken");

module.exports = (req, res, next) => {
try {
const token = req.headers.authorization.split(" ")[1];
jwt.verify(token, "this_is_the_secret");
next();
} catch (error) {
res.status(401).json({ message: "Auth failed!" });
}
};

中间件植入

router.post('/orders', checkAuth, function(req,res,next){
Order.create(req.body.order, function(err, createdOrder){
if (err) return next(err)
.then()
Show.findByIdAndUpdate({"_id": req.body.showId}, {"$push":{"takenSeats": req.body.takenSeatsIds}})
.exec(function(err, updatadShow){
if (err) return next(err)
console.log(updatadShow)
})
res.json(createdOrder)
})
})

Angular 验证服务

import { Injectable } from "../../../node_modules/@angular/core";
import { HttpClient } from "../../../node_modules/@angular/common/http";
import { AuthData } from "../models/auth-data.model";

@Injectable({ providedIn: "root"})
export class AuthService {
private token: string

signupUrl = "http://localhost:3000/signup";
loginUrl = "http://localhost:3000/login"

constructor(private http: HttpClient){}

getToken(){
return this.token
}


createUser(email: string, password:string){
const authData: AuthData = {email: email, password: password}
this.http.post(this.signupUrl, authData)
.subscribe(response => {
console.log(response)
});
}


login(email: string, password){
const authData: AuthData = {email: email, password: password}
this.http.post<{token: string}>(this.loginUrl,authData)
.subscribe(response => {
console.log(response)
const token = response.token
this.token = token;
console.log("token" + this.token)
});
}
}

AuthInterceptor服务

import { HttpInterceptor, HttpRequest, HttpHandler } from "../../../node_modules/@angular/common/http";
import { Injectable } from "../../../node_modules/@angular/core";
import { AuthService } from "./auth.service";


@Injectable()
export class AuthInterceptor implements HttpInterceptor {

constructor(private authService:AuthService){}

intercept(req: HttpRequest<any>, next: HttpHandler) {
const authToken = this.authService.getToken();
const authRequest = req.clone({
headers: req.headers.set('Authorization', "Bearer" + authToken)
})
return next.handle(authRequest)
}
}

[编辑]身份验证 token 的状态

登录响应的console.log

{token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6I…Q3OH0.fCgCuHQkDHHgJHq8LFqeVxLayyr-9U-Y6_23_9FGHkU", expiresIn: 3600}
auth.service.ts:35 tokeneyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Imlnb3JybzYyMUBnbWFpbC5jb20iLCJ1c2VySWQiOiI1YjU4YjYwYTUxMDkyNDI4Njg1MDM3MzIiLCJpYXQiOjE1MzI1NDc4NzgsImV4cCI6MTUzMjU1MTQ3OH0.fCgCuHQkDHHgJHq8LFqeVxLayyr-9U-Y6_23_9FGHkU

在未实现中间件的情况下发布到路由后的 req.headers.authorization 的 console.log

BearereyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Imlnb3JybzYyMUBnbWFpbC5jb20iLCJ1c2VySWQiOiI1YjU4YjYwYTUxMDkyNDI4Njg1MDM3MzIiLCJpYXQiOjE1MzI1NDc4NzgsImV4cCI6MTUzMjU1MTQ3OH0.fCgCuHQkDHHgJHq8LFqeVxLayyr-9U-Y6_23_9FGHkU

中间件函数内部状态的console.log

记录点

const jwt = require("jsonwebtoken");

module.exports = (req, res, next) => {
try {
console.log(" Before the split " + req.headers.authorization)
const token = req.headers.authorization.split(" ")[1];
console.log(" After The split " + req.headers.authorization)
jwt.verify(token, "this_is_the_secret");
next();
} catch (error) {
res.status(401).json({ message: "Auth failed!" });
}
};

结果

 Before the split BearereyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Imlnb3JybzYyMUBnbWFpbC5jb20iLCJ1c2VySWQiOiI1YjU4YjYwYTUxMDkyNDI4Njg1MDM3MzIiLCJpYXQiOjE1MzI1NDc4NzgsImV4cCI6MTUzMjU1MTQ3OH0.fCgCuHQkDHHgJHq8LFqeVxLayyr-9U-Y6_23_9FGHkU
After The split BearereyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6Imlnb3JybzYyMUBnbWFpbC5jb20iLCJ1c2VySWQiOiI1YjU4YjYwYTUxMDkyNDI4Njg1MDM3MzIiLCJpYXQiOjE1MzI1NDc4NzgsImV4cCI6MTUzMjU1MTQ3OH0.fCgCuHQkDHHgJHq8LFqeVxLayyr-9U-Y6_23_9FGHkU

最佳答案

好的。我发现了问题所在,我没有在 “Bearer”之后添加空格HttpInterceptor

关于node.js - 在 Angular 6 + Node js 中使用 token 的身份验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51526401/

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