使用passport

编程入门 行业动态 更新时间:2024-10-24 05:19:58
本文介绍了使用passport-jwt授权jwt令牌时获得401未授权状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

成功登录后,我得到了 jwt 令牌,现在要访问受限制的 api,我正在发送授权标头,但我总是得到

401 未经授权

我已经提到了这个使用passport-jwt验证节点API这里提出的问题,但没有帮助我,

这是我调用的函数,用于从受限 api 访问数据

check() {控制台日志(this.token);var headers = new headers();headers.append('Content-Type', 'application/json');headers.append("Authorization", "Bearer" + this.token);让 url = this.authenticationEndPoint + 'random';this.checkauth(url, headers).subscribe(数据 =>{控制台日志(数据);},错误 =>{console.log("错误");});}checkauth(url:string, header:any): Observable{返回 this.http.get(url, header).map(this.extractData).catch(this.handleError);}私人提取数据(资源:响应){让身体 = res;返回正文 ||{};}

在我的 nodeJs 服务器上,这里是发送 jwt 令牌的登录代码:

app.post('/login_mobile', function(req, res) {if(!(req.body.email && req.body.passpord)) {user.findOne({'local.email' : req.body.email}, function(err, user) {如果(错误){ 返回完成(错误);}如果(!用户){return res.json(200, "邮箱错误");}if(!user.validPassword(req.body.password)) {return res.json(200, "密码错误");}var token = jwt.encode(user, configAuth.secret);return res.json(200, { user: user, jwtToken: token });});}别的 {res.send("未提供凭据");}});

响应受限api请求的代码

app.get('/random',passport.authenticate('jwt', { session: false }),功能(请求,资源){res.send("成功");});

这是我用来验证用户身份的通行证策略,但奇怪的是它甚至没有打印此处仍然发送 401 状态.

var opts = {};opts.secretOrKey = configAuth.secret;opts.jwtFromRequest = ExtractJwt.fromAuthHeader();护照.使用(新的JwtStrategy(选择,功能(jwt_payload,完成){console.log("这里");控制台日志(jwt_payload);User.findOne({_id: jwt_payload._id}, function(err, found_user) {如果(错误){返回完成(错误,错误);}if(found_user !== null) {res.send("终于");}别的 {res.send("认证失败");}返回 found_user ?完成(空,发现用户):完成(空,假);})}));

如果有人可以指出我的错误.

解决方案

我修复了一个类似的问题替换:

jwtFromRequest: ExtractJwt.fromAuthHeader(),

与:

jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),

After successfully logging in I am getting the jwt token, now to access restricted api's I am sending the authorization header, but I am always getting

401 Unauthorized

I have referred to this Authenticating node API with passport-jwt question asked here but didn't helped me,

this is the function I am calling for accessing data from resticted api

check() { console.log(this.token); var headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append("Authorization", "Bearer" + this.token); let url = this.authenticationEndPoint + 'random'; this.checkauth(url, headers).subscribe( data => { console.log(data); }, error => { console.log("error"); } ); } checkauth(url:string, header:any): Observable<any> { return this.http.get(url, header) .map(this.extractData) .catch(this.handleError); } private extractData(res: Response) { let body = res; return body || {}; }

On my server in nodeJs here is the login code sending the jwt token:

app.post('/login_mobile', function(req, res) { if(!(req.body.email && req.body.passpord)) { user.findOne({'local.email' : req.body.email}, function(err, user) { if (err) { return done(err);} if (!user) { return res.json(200, "email is wrong"); } if(!user.validPassword(req.body.password)) { return res.json(200, "wrong password"); } var token = jwt.encode(user, configAuth.secret); return res.json(200, { user: user, jwtToken: token }); }); } else { res.send("no credentials provided"); } });

code for responding to restricted api request

app.get('/random', passport.authenticate('jwt', { session: false }), function(req, res) { res.send("success"); });

this is the passport strategy I am using to authenticate user, but strangely it is not even printing here still it is sending 401 status.

var opts = {}; opts.secretOrKey = configAuth.secret; opts.jwtFromRequest = ExtractJwt.fromAuthHeader(); passport.use(new JwtStrategy(opts, function(jwt_payload, done){ console.log("here"); console.log(jwt_payload); User.findOne({_id: jwt_payload._id}, function(err, found_user) { if (err) { return done(err, false); } if(found_user !== null) { res.send("finally"); } else { res.send("authentication failed"); } return found_user ? done(null, found_user) : done(null, false); }) }));

If someone can please point out my mistake.

解决方案

I fixed a similar problem replacing:

jwtFromRequest: ExtractJwt.fromAuthHeader(),

with:

jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),

更多推荐

使用passport

本文发布于:2023-11-16 21:08:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607462.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:passport

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!