【发布时间】:2015-05-28 11:56:23
【问题描述】:
我已经为此苦苦挣扎了几个小时,需要一些帮助。我创建了一个简单的应用程序,该应用程序在将用户重定向到 Google Oauth 页面的角度视图中向用户显示“使用 Google 登录”按钮。这是按下按钮时调用 login() 函数的控制器代码:
angular.module('dashApp').controller('SigninCtrl', function ($scope) {
$scope.login=function() {
var client_id="191641883719-5eu80vgnbci49dg3fk47grs85e0iaf9d.apps.googleusercontent.com";
var scope="email";
var redirect_uri="http://local.host:9000/api/auth/google";
var response_type="code";
var url="https://accounts.google.com/o/oauth2/auth?scope="+scope+"&client_id="+client_id+"&redirect_uri="+redirect_uri+
"&response_type="+response_type;
window.location.replace(url);
};
});
我的google项目中设置的redirect URI重定向到一个服务器页面到这个服务器页面:
'use strict';
var _ = require('lodash');
var request = require('request');
var qs = require('querystring');
var fs = require('fs');
// Get list of auths
exports.google_get = function (req,res){
var code = req.query.code,
error = req.query.error;
if(code){
//make https post request to google for auth token
var token_request = qs.stringify({
grant_type: "authorization_code",
code: code,
client_id: "191641883719-5eu80vgnbci49dg3fk47grs85e0iaf9d.apps.googleusercontent.com",
client_secret: process.env.GOOGLE_SECRET,
redirect_uri: "http://local.host:9000/api/auth/google"
});
var request_length = token_request.length;
var headers = {
'Content-length': request_length,
'Content-type':'application/x-www-form-urlencoded'
};
var options = {
url:'https://www.googleapis.com/oauth2/v3/token',
method: 'POST',
headers: headers,
body:token_request
};
request.post(options,function(error, response, body){
if(error){
console.error(error);
}else{
//WHAT GOES HERE?
}
});
}
if(error){
res.status(403);
}
}
我能够成功地将 google 返回的代码交换为身份验证令牌对象并将其记录到终端。有人告诉我应该使用以下方法设置 cookie:
res.setHeader('Content-Type', 'text/plain');
res.setCookie('SID','yes',{
domain:'local.host',
expires:0,
path:'/dashboard',
httpOnly:false
});
res.status(200);
res.end();
随后是页面上的控制器,我将用户引导至验证会话。
我做错了什么?
【问题讨论】:
-
我没看到你有什么问题。
-
我意识到我需要让 Angular 控制器向服务器执行一个 get 请求,以便对浏览器进行初始重新路由 - 现在正在处理这个问题。完成后我会发布代码更新。
标签: angularjs node.js cookies express oauth