【发布时间】:2017-03-16 12:59:22
【问题描述】:
我正在使用 MEAN 堆栈构建的 SPA 中实现 fb 身份验证。虽然我已经使用 facebook 令牌通行证策略成功实现了 fb 身份验证,但我在保护 API 端点方面遇到了问题。因为为此我需要在 $http 服务中传递经过身份验证的用户对象和访问令牌,并且我尝试将 access_token 作为用户对象的属性和标头属性传递,但我仍然是 401(未经授权的错误)。下面是我的代码 sn-p。
护照文档说“授权:Bearer base64_access_token_string”。令牌是否应该以 base64 格式编码?请帮忙。
服务器代码
app.get('/api/getbikes*',
passport.authenticate('facebook-token',{session: false}),
function(req,res){
if(req.user){
console.log('In getbikes api');
// console.log('req.query :',req.query);
var msg="";
ubBike
.find({cust:req.query._id})
.populate('cust','email')
.exec(function(err,bikes){
res.send(bikes);
if(err) throw err;
});
}
else
{
res.send(401);
}
});
角码
服务
this.getbikes = function(user){
var deferred = $q.defer();
$http({
method:"GET",
url:"http://localhost:3000/api/getbikes",
params: user,
headers:{
Authorization:auth.getAccesstoken()
}
}).then(function successCallback(srresponse){
deferred.resolve(srresponse.data);
},
function failureCallback(srresponse){
$log.error("get bikes http call failed ",srresponse.data);
deferred.reject(srresponse.data);
});//$http
return deferred.promise;
};//getbikes
控制器
$scope.fblogin= function(){
auth.fblogin().then(
function(response){
$scope.isAuth = auth.isAuth;
$scope.usr =auth.getResponseobj();
$scope.usr.access_token=auth.getAccesstoken();
$scope.profpic=auth.profpic;
bike.getbikes($scope.usr).then(function(response){
if (response.length ==0)
{
$location.path('/addbike');//redirect to addbike screen
}
else{
$location.path('/appoint');//else redirect to view appointment screen
}
},function(reason){
$scope.msg1 = reason;
});//getbikes
},function(reason){
$log.log("fblogin() - failure :Need to login to the application :"+reason);
})
};//fblogin
【问题讨论】:
-
如果您在 http 标头中发送 accesstoken,那么它应该采用这种格式
Authorization: Bearer accesstokenstring。你的标题授权是这样形成的吗?同样在您的控制器中,您发送的是$scope.usr而不是user。请也检查一下。 -
也尝试调试您的服务器代码并找出您的
req对象包含什么? -
@Karthik,“Bearer accesstokenstring”格式是什么意思?那是我最初被卡住的地方。这是否意味着在令牌前面加上“Bearer”。请澄清
-
检查这个 - stackoverflow.com/a/18752897/1210896。这就是我们将授权信息作为 API 请求的 HTTP 标头的一部分发送的方式。
-
感谢我能够在注入 base64 依赖项和 $base64 服务后对令牌进行编码。我不再收到 401(未经授权)错误。但是我得到一个 500(内部服务器错误)并且节点日志给出了以下错误。 InternalOAuthError:无法在 D:\Raj\important\youbike\node_modules\passport-facebook-token\lib\index.js:155:32 在 passBackControl (D:\Raj\important\youbike\node_modules\passport- facebook- token\node_modules\passport-oauth\node_modules\passport-oauth2\node_modules\oaut h\lib\oauth2.js:123:9) 在 IncomingMessage.
标签: angularjs http passport-facebook