我的代码在POSTMAN上工作正常,但是当我尝试使用浏览器时,它会在控制台中显示此错误:
http://localhost:3000/users/profile 401 (Unauthorized)
我正在尝试使用PASSPORT JWT进行身份验证。 我的认真路线:
http://localhost:3000/users/profile
我的护照配置文件:
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
const database = require("./database");
const User = require("../model/model");
module.exports = (passport) => {
var opts = {}
opts.jwtFromRequest = ExtractJwt.fromHeader("authorization");
opts.secretOrKey = database.secret;
// console.log(opts);
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
// console.log(jwt_payload);
User.findById(jwt_payload._id, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
}
我的令牌在这里创建(这是登录端点):
router.post('/authUserCredentials', (req, res, next)=>{
var userCred = req.body;
// console.log(userCred);
controllers.checkUserExist({email : req.body.email}, (err, data) => {
if(err){
controllers.failResponse(res, "Something went wrong. Please try again.");
}else if(!data){
controllers.failResponse(res, "You Are Not Registered. Please Register to Continue.");
}else{
var passMatch = controllers.comparePassword(userCred.password, data.password);
// console.log(passMatch);
if(!passMatch){
controllers.failResponse(res, "Invalid Email or Password. Please try again.");
}else{
var token = jwt.sign(data.toJSON(), database.secret, {expiresIn: 604800});
res.json({
success: true,
msg: "Login Successful.",
token: token
});
}
}
});
});
获取用户个人资料的护照路径(用户登录后):
router.get('/profile', passport.authenticate('jwt', { session: false }), (req, res, next) => {
res.json({user: req.user});
});
我在此处提交表单和有效回复后,我的令牌存储在本地存储中:
authUserCredentials()
{
console.log(this.loginUser.value);
var email = this.loginUser.value.email.toLowerCase().trim();
var password = this.loginUser.value.password.trim();
var loginUserData = {email, password};
console.log(loginUserData);
this.userServ.authUser(loginUserData).subscribe((data:any) => {
if(!data.success){
this.flashMsg.show("ERROR : "+ data.msg, {cssClass: 'flashMessageBox', timeout: 5000});
this.router.navigate(['/']);
}else{
this.userServ.storeToken(data.token);
this.flashMsg.show("SUCCESS : "+ data.msg, {cssClass: 'flashMessageBox', timeout: 5000});
this.router.navigate(['user/profile']);
}
})
}
我的个人资料角度分量:
ngOnInit() {
this.userServ.getUserProfile().subscribe((data:any)=>{
console.log(data);
this.user = data.user;
// console.log(data);
},err => {
console.log(err);
return false;
});
}
获取用户个人资料服务并存储令牌并获取令牌功能:
getUserProfile(){
let header = new HttpHeaders();
var token = this.getToken();
// console.log(token);
header.append('Authorization', token);
header.append('Content-Type', 'application/json');
// console.log(header);
return this.http.get('http://localhost:3000/users/profile', {headers: header}).map(res => {return res});
}
storeToken(token){
localStorage.setItem('id_token', token);
}
getToken(){
return localStorage.getItem('id_token');
}
答案 0 :(得分:0)
试试这个:
header.append('Authorization', `Bearer ${token}`);
答案 1 :(得分:0)
像这样更改您的个人档案服务功能标头追加
header = header.append('Authorization', token);
header = header.append('Content-Type', 'application/json');
答案 2 :(得分:0)
首先去authinterceptor.ts 用上面的代码替换现有代码
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from "@angular/common/http";
import { Injectable } from '@angular/core';
import { tap } from 'rxjs/operators';
import { Router } from "@angular/router";
import { UserService } from "../user/user-services/user.service";
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private userService : UserService,private router : Router){}
intercept(req: HttpRequest<any>, next: HttpHandler) {
if (req.headers.get('noauth'))
return next.handle(req.clone());
else {
const clonedreq = req.clone({
headers: req.headers.set("Authorization", this.userService.loadToken())
});
return next.handle(clonedreq).pipe(
tap(
event => { },
err => {
if (err.error.auth == false) {
this.router.navigateByUrl('/login');
}
})
);
}
}
}