使用MEAN Stack,我使用jsonwebtoken设置了身份验证,并且能够使用jsonwebtoken从后端生成令牌,但是它从前端的auth-interceptor服务返回未定义的内容。请参阅下面的片段。谢谢
auth-interceptor.ts服务
import { Injectable } from "@angular/core";
import { HttpInterceptor, HttpRequest, HttpEvent, HttpHandler } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authUser: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authToken = this.authUser.getToken();
console.log(authToken); //but this return undefined
if(authToken) {
req = req.clone({
headers: req.headers.set("Authorization", "Bearer " + authToken)
});
}
return next.handle(req);
}
}
auth-service.ts服务
import { Injectable } from "@angular/core";
import { HttpClient } from '@angular/common/http';
import { User } from "./user.model";
@Injectable({ providedIn: "root" })
export class AuthService {
private token: string;
constructor(private http: HttpClient) {}
getToken() {
return this.token;
}
login(Email: string, Password: string) {
const userAuth: User = { Email: Email, Password: Password,
Firstname:null, Lastname:null, CourseStudied:null, AcademyAward:null,
Photo:null, id:null, AreaSpecialised:null};
this.http.post<{token: string}>("http://localhost:3000/api/users/login/", userAuth)
.subscribe(response => {
const token = response.token;
this.token = token;
console.log(this.token) //this returns the token
});
}
}
我的app.modules.ts的一部分
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
MDBSpinningPreloader, UsersService,
],
我的中间件-我也console.log令牌,它有效
const jwt = require("jsonwebtoken");
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization.split(" ")[1];
jwt.verify(token, "sjoigej34989wejsdijfi!8Z()&iuhusdh3wn2sjj5JDU3u5fksl)k2=SDKOFO322KSMFIIMMK1K4K#@^5JDLK9kskd");
next();
} catch (error) {
res.status(401).json({ message: "You are not authorized!"});
}
}
这是我登录的明确途径。我也在console.log上记录了令牌,并且可以正常工作
router.post("/login", (req, res, next) => {
let fetchedUser;
User.findOne({Email: req.body.Email}).then(user => {
if (!user) {
return res.status(401).json({
message: 'Auth failed - Either email or password is incorrect'
});
}
fetchedUser = user;
return bcrpt.compare(req.body.Password, user.Password);
})
.then (result => {
if(!result) {
return res.status(401).json({
message: 'Auth failed - Either email or password is incorrect'
});
}
const token = jwt.sign(
{Email:fetchedUser.Email, userId: fetchedUser._id, username: fetchedUser.Firstname + ' ' + fetchedUser.Lastname},
"sjoigej34989wejsdijfi!8Z()&iuhusdh3wn2sjj5JDU3u5fksl)k2=SDKOFO322KSMFIIMMK1K4K#@^5JDLK9kskd",
{ expiresIn: "0.25h"}
);
res.status(200).json({
token: token
});
})
.catch(err => {
return res.status(401).json({
message: 'Auth failed - Either email or password is incorrect'
})
})
令牌仅到达前端的auth-interceptor.ts。拜托,我只是这里的新手,帮帮我。
答案 0 :(得分:0)
您应该做的是将令牌存储在浏览器会话中,而不是存储在类本身上。
将login
中的AuthService
方法更改为:
login(Email: string, Password: string) {
const userAuth: User = {
Email: Email, Password: Password,
Firstname: null, Lastname: null, CourseStudied: null, AcademyAward: null,
Photo: null, id: null, AreaSpecialised: null
};
this.http.post<{ token: string }>("http://localhost:3000/api/users/login/", userAuth)
.subscribe(response => {
const token = response.token;
localStorage.setItem('token', token);
console.log(token) //this returns the token
});
}
并添加此方法:
getToken(): string {
return localStorage.getItem('auth_token');
}
并将intercept
中的AuthInterceptor
方法更改为:
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authToken = this.authenticationService.getToken();
console.log(authToken); //but this return undefined
if(authToken) {
req = req.clone({
headers: req.headers.set("Authorization", "Bearer " + authToken)
});
}
return next.handle(req);
}