【发布时间】:2020-07-29 19:43:10
【问题描述】:
我正在尝试构建一个简单的应用程序来验证 twitch 帐户并显示用户信息。一旦用户成功登录,我就无法发送我的身份验证代码。
服务器端,我的代码如下:
---auth-routes.js
// auth with twitch
router.get("/twitch", passport.authenticate("twitch", { scope: "user_read" }), (req, res) => {
res.status(200).json({message: 'Authenticating...'});
console.log('Authenticating...')
});
// redirect to home page after successful login via twitch
router.get(
"/twitch/redirect",
passport.authenticate("twitch", {
successRedirect: "/auth/twitch/redirect",
failureRedirect: "/auth/login/failed"
})
);
---config/passport-setup.js
// Override passport profile function to get user profile from Twitch API
OAuth2Strategy.prototype.userProfile = function(accessToken, done) {
var options = {
url: 'https://api.twitch.tv/helix/users',
method: 'GET',
headers: {
'Client-ID': TWITCH_ID,
'Accept': 'application/vnd.twitchtv.v5+json',
'Authorization': 'Bearer ' + accessToken
}
};
request(options, function (error, response, body) {
if (response && response.statusCode == 200) {
done(null, JSON.parse(body));
} else {
done(JSON.parse(body));
}
});
}
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use('twitch', new OAuth2Strategy({
authorizationURL: 'https://id.twitch.tv/oauth2/authorize',
tokenURL: 'https://id.twitch.tv/oauth2/token',
clientID: TWITCH_ID,
clientSecret: TWITCH_SECRET,
callbackURL: TWITCH_CB,
state: true
},
function(accessToken, refreshToken, profile, done) {
profile.accessToken = accessToken;
profile.refreshToken = refreshToken;
console.log(profile);
// Securely store user profile in your DB
//User.findOrCreate(..., function(err, user) {
// done(err, user);
//});
done(null, profile);
}
))
我还有一个简单的配置文件组件,当 auth/twitch/redirect 路由被命中时显示
export const AppRouter = () => {
return (
<Router>
<div>
<Route exact path='/' component={HomePage} />
<Route path='/auth/twitch/redirect' component={Profile} />
</div>
</Router>
)
}
根据 twitter 文档,您需要获取附加到重定向 URI 的访问代码并使用它进行发布请求。我无法弄清楚如何以及在何处提取该代码并将其发送。这是他们在文档中所说的:
在我们的示例中,您的用户被重定向到:
http://localhost/?code=394a8bc98028f39660e53025de824134fb46313
&scope=viewing_activity_read
&state=c3ab8aa609ea11e793ae92361f002671
3) 在您的服务器上,通过发出以下请求获取访问令牌:
POST https://id.twitch.tv/oauth2/token
?client_id=<your client ID>
&client_secret=<your client secret>
&code=<authorization code received above>
&grant_type=authorization_code
&redirect_uri=<your registered redirect URI>
这是一个示例请求:
POST https://id.twitch.tv/oauth2/token
?client_id=uo6dggojyb8d6soh92zknwmi5ej1q2
&client_secret=nyo51xcdrerl8z9m56w9w6wg
&code=394a8bc98028f39660e53025de824134fb46313
&grant_type=authorization_code
&redirect_uri=http://localhost
感谢您的帮助!
【问题讨论】:
标签: node.js oauth-2.0 passport.js twitch