【问题标题】:How to handle twitch passport.js auth code?如何处理 twitch passport.js 验证码?
【发布时间】: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


    【解决方案1】:

    我正在努力解决同样的问题。不过,我想我可能会有所帮助。 我还看到这是一个有点旧的帖子,所以你可能已经想通了。 要使用路由器从 URL 中获取哈希或片段,您可以:

    import React, { useEffect } from "react";
    import { useLocation } from "react-router-dom";
    
    const yourCallbackComponent = () => {
    
      let location = useLocation();
      useEffect(() => {
        console.log(location)
      }, [location])
    
      return ()
    }
    

    我写的很匆忙,如果写的不好,请见谅。但是,当加载路线时,您可以在位置对象中提取信息。

    console.log 的预期输出应该在这个附近:

    {
      key: 'ac3df4', // not with HashHistory!
      pathname: '/somewhere',
      search: '?access_token:jf82rjfj02f0f',
      hash: '#access_tokenjf82rjfj02f0f',
      state: {
        [userDefined]: true
      }
    }
    

    它要么在散列中,要么在搜索中,这取决于你从 twitch 得到什么。 如果您还没有找到解决方案,希望这对您有所帮助。

    我仍在尝试自己弄清楚接下来的步骤,因此我无法提供任何帮助。 如果您仍然卡住,请告诉我,当我弄清楚它是如何工作时,我会发布我的发现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2017-01-01
      • 2021-09-02
      • 2010-11-18
      • 2015-06-10
      • 1970-01-01
      • 2019-07-26
      相关资源
      最近更新 更多