我正在研究在 MEAN 堆栈上运行的 WebApplication(遵循 TraversyMedia 教程)。但是,我遇到了一个问题,这里提供的解决方案似乎都不适合我。每当我尝试访问我的 /profile 页面(除非您获得授权,否则该页面受保护)时,我都会返回错误。但是,我已登录并拥有正确的访问令牌。
我查看了passport-jwt git。但我所拥有的似乎匹配。我曾尝试使用:
ExtractJwt.fromAuthHeaderWithScheme("bearer");
ExtractJwt.fromAuthHeaderWithScheme("bearer");
ExtractJwt.fromAuthHeaderAsBearerToken();
目前使用: ExtractJwt.fromAuthHeaderWithScheme("bearer") 因为没有显示出差异。
我查看了 HttpClientModule,但我的电话似乎没问题。
护照.js
module.exports = function(passport) {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme("bearer");
opts.secretOrKey = config.secret;
passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
User.getUserById(jwt_payload.data._id, (err, user) => {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
})
);
};
用户.js
const express = require("express");
const router = express.Router();
const passport = require("passport");
const jwt = require("jsonwebtoken");
const config = require("../config/database");
const User = require("../models/user");
...
router.get(
"/profile",
passport.authenticate("jwt", { session: false }),
(req, res, next) => {
res.json({ user: req.user });
}
);
module.exports = router;
auth.service.ts
import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { map } from "rxjs/operators";
// Left some unrelated stuff out here
export class AuthService {
authToken: any;
user: any;
constructor(private http: HttpClient) {}
...
getProfile() {
let headers = new HttpHeaders();
this.loadToken();
headers.append("authorization", this.authToken);
headers.append("Content-Type", "application/json");
return this.http
.get("http://localhost:3000/users/profile", {
headers: headers
})
.pipe(map(res => res));
}
...
loadToken() {
const token = localStorage.getItem("id_token");
this.authToken = token;
}
profile.component.ts
export class ProfileComponent implements OnInit {
user: Object;
constructor(private authService: AuthService, private router: Router) {}
ngOnInit() {
this.authService.getProfile().subscribe(
profile => {
this.user = profile.user;
},
err => {
console.log(err);
return false;
}
);
}
}
预计将被定向到个人资料页面,但我得到的是:
GET http://localhost:3000/users/profile 401 (Unauthorized)
HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "Unauthorized", url: "http://localhost:3000/users/profile", ok: false, …}
error: "Unauthorized"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://localhost:3000/users/profile: 401 Unauthorized"
name: "HttpErrorResponse"
ok: false
status: 401
statusText: "Unauthorized"
url: "http://localhost:3000/users/profile"