在angular 6 + node js中使用令牌的身份验证问题

时间:2018-07-25 19:32:15

标签: node.js angular

我试图用Node js作为我的服务器来构建一个Authentication函数, 我对从angular发送的令牌的标识有疑问。 我使用有角的HttpInterceptor服务处理标头,并在节点js中创建了一个middelware函数。我收到的错误是:

{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)
    })
})

角度认证服务

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)
    }
}

[编辑]身份验证令牌的状态

登录响应的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

1 个答案:

答案 0 :(得分:0)

好的。我发现了问题所在,在"Bearer "之后没有放空格 在HttpInterceptor