【问题标题】:How to fix '401 Unauthorized' Passport-jwt + Angular? [duplicate]如何修复'401 Unauthorized' Passport-jwt + Angular? [复制]
【发布时间】:2019-12-05 17:41:52
【问题描述】:

我正在开发在 MEAN 堆栈上运行的 Web 应用程序(遵循 TraversyMedia 教程)。但是,我遇到了一个问题,这里提供的解决方案似乎都不适合我。每当我尝试访问我的 /profile 页面(除非您获得授权,否则该页面受到保护),我都会收到错误返回。但是,我已登录并拥有正确的访问令牌。

我查看了 passport-jwt git。但我所拥有的似乎匹配。 我曾尝试使用: ExtractJwt.fromAuthHeaderWithScheme("bearer"); ExtractJwt.fromAuthHeaderWithScheme("bearer"); ExtractJwt.fromAuthHeaderAsBearerToken();

目前正在使用: ExtractJwt.fromAuthHeaderWithScheme("bearer") 因为没有任何区别。

我查看了 HttpClientModule,但我的调用似乎没问题。

passport.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);
        }
      });
    })
  );
};

users.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"

【问题讨论】:

  • 你能提供一个最小的工作示例吗?
  • 问题已解决。对于其他有同样问题的人来说,为我解决的问题是:替换:`let headers = new HttpHeaders(); this.loadToken(); headers.append("授权", this.authToken); headers.append("Content-Type", "application/json"); ` With: ` const headers = new HttpHeaders({ "Content-Type": "application/json", Authorization: this.authToken }); this.loadToken(); `
  • 如果您的问题已解决,请考虑发布自我回答,以免问题显示为“未回答”。

标签: node.js angular jwt passport-jwt


【解决方案1】:

问题已解决。对于其他有同样问题的人来说,为我解决的问题是:替换:

let headers = new HttpHeaders(); this.loadToken(); headers.append("authorization", this.authToken); headers.append("Content-Type", "application/json");

与:

const headers = new HttpHeaders({ "Content-Type": "application/json", Authorization: this.authToken }); this.loadToken();

【讨论】:

    猜你喜欢
    • 2021-10-11
    • 1970-01-01
    • 2020-07-05
    • 2014-08-19
    • 2018-08-06
    • 2015-03-13
    • 2021-05-28
    • 2021-09-09
    • 2020-05-11
    相关资源
    最近更新 更多