node.js app でトークンベースの認証を構築する必要があります。ユーザーは自分の Facebook または Twitter 資格情報を使用してアプリにログインし、アクセス トークンを使用してリソースにアクセスできます。この投稿は、FacebookやTwitterなどで認証されたら、すべてのリクエストでアクセストークンを使用する ことを提案しています。たとえば、セッションはまったく必要ありません
GET /api/v1/somefunction?token='abcedf'
- クライアントは、応答からアクセス トークンを取得します。
- クライアントは、トークン引数を使用してサーバー API を呼び出します。
したがって、次のコードは、アプリがユーザー情報を見つけられない場合に、Twitter を介してユーザーを承認し、ユーザー情報をデータベースに保存することです。
passport.use(new TwitterStrategy({
consumerKey: config.twitter.clientID,
consumerSecret: config.twitter.clientSecret,
callbackURL: config.twitter.callbackURL
},
function(token, tokenSecret, profile, done) {
console.log('TwitterStrategy /auth/twitter.............',profile.id, profile.displayName, profile.username, profile.emails[0], profile._json.avatar_url);
userModel.findUserByQuery({ 'social.twitter.id': profile.id }, function (err, user) {
if (!user) {
console.log('twitter user not found'.red);
userModel.createNewUser( { username:profile.username,
email:profile.emails[0].value,
img:profile._json.avatar_url,
fullname:profile.displayName,
password:profile._json.avatar_url,
social:{twitter:{id:profile.id,avatar:profile._json.avatar_url, name:profile.username,token:accessToken} }},
function(err,data){
if(err) return done(err);
else if(!data) return done(null, false, { message: 'can not create your profile in database' });
else {
console.log('save the new twitter user into database'.green, data._id);
return done(err, user);
}
})
} else {
console.log('twitter user found'.green);
return done(err, user);
}
})
}
))
ただ、質問が2点ありますので、
1.以下のリクエストでクライアントにアクセストークンを送信する方法
コードでは、twitterから認証後、アクセストークンを取得し、このトークンをブラウザ上のクライアントに送信します.トークンはurlパラメーターに埋め込まれているので、コード res.redirect('/users/profile?token = blabla ') ですが、クライアント ブラウザーでは、URL は「/users/profile ?」ではなく「/users/profile」として表示されます。トークン=blabla'
2. Twitter から認証されると、トークンを使用した次の要求がローカルでアプリを通過します (トークンをデータベースに保存し、次のトークンを比較して検証します)、または認証のために Twitter API に送信しますか?
最初の状況の場合、トークンをデータベースに保存して、次のリクエストのトークンで次のリクエストをアプリに比較する必要がありますか? そうですか