我正在编写一个小型node.js Web应用程序,它需要Google API并使用OAuth2作为身份验证机制。我注意到在请求访问令牌时有些奇特 - 在允许从对象访问更改类型到字符串后收到的“代码”。在“建筑物中的OAuth”之后记录响应类型。
很抱歉,如果这是一个重复的问题。
路线:
handle['/connect'] = requestHandlers.connect;
handle['/oauth2callback'] = requestHandlers.oauth;
路由器:
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function'){
handle[pathname](response);
if (pathname === '/oauth2callback'){
handle[pathname](query);
}
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not found");
response.end();
}
处理程序:
function connect(response){
console.log("Request Handler 'start' was called.");
auth.access(response);
}
function oauth(response){
console.log("OAuth in the building. This is the instance: ");
if(typeof response !== 'undefined'){
if(typeof response == "string"){
var code = response.split("code=").pop();
auth.exchange(code);
}else {
console.log("This response isn't ready until it is a string. It has these values: " + Object.getPrototypeOf(response));
}
}
}
验证
function getAccess(response){
var url = authClient.generateAuthUrl({
access_type: 'offline',
scope: 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/calendar.readonly'
});
console.log("[Auth.js] This is the response received: " + Object.keys(response));
response.writeHead(302,{
"Location":url
});
response.end();
}
function exchangeToken(code){
authClient.getToken(code,function(err,tokens){
console.log("We got some tokens! " + tokens);
});
console.log("Authorized");
}