我的项目使用HttpClientModule,HttpClient和passport.js与passport-jwt。我的目标是保护/ user / profile路由(呈现一个实际上为空白的ProfileComponent),但我总是收到一条未经授权的消息,因为在访问它之前我无法设置标头。我尝试使用Interceptor(authInterceptor),但它只拦截http请求,而不是直接访问该路由。以下是我使用的文件:
的AppModule
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
SearchComponent,
],
imports: [
AppRoutingModule,
FormsModule,
NgbModule.forRoot(),
BrowserModule,
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
export class AppModule {
}
SigninComponent (从被动表单中检索值并向方法提交信息"在AuthService中登录"
onSubmit() {
const user = new User('user', this.signinForm.value.email, this.signinForm.value.password);
this.authService.signin(user)
.subscribe(
data => {
localStorage.setItem('token', data['token']);
localStorage.setItem('userId', data['userId']);
this.router.navigateByUrl('/');
},
error => console.error(error)
);
}
登录方式
signin(user: User) {
let headers: HttpHeaders = new HttpHeaders();
headers.set('Content-type', 'application/json');
return this.http.post('http://localhost:3000/user/signin', user, {headers: headers})
}
AuthInterceptor (我认为它总是设置标题,甚至直接访问路径,但它不是。我正在使用它"如果"因为& #34; getItem"返回null)
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (localStorage.getItem('token')) {
req = req.clone({
setHeaders: {
Authorization: localStorage.getItem('token')
}
});
}
return next.handle(req);
}
}
User.js (节点路线)
router.post('/signin', function (req, res, next) {
User.findOne({email: req.body.email}, function (err, user) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!user) {
return res.status(401).json({
title: 'Login failed',
error: {message: 'Invalid login credentials'}
});
}
if (!bcrypt.compareSync(req.body.password, user.password)) {
return res.status(401).json({
title: 'Login failed',
error: {message: 'Invalid login credentials'}
});
}
let payload = {id: user._id, username: user.username, email: user.email};
let token = jwt.sign(payload, keys.secretOrKey, {expiresIn: 7200});
res.status(200).json({
message: 'Successfully logged in',
token: 'Bearer ' + token,
userId: user._id
});
});
});
router.get('/profile', passport.authenticate('jwt', { session: false }),
function(req, res) {
res.json({ id: req.user.id, username: req.user.username });
});
答案 0 :(得分:0)