LoginSignup
2
1

More than 1 year has passed since last update.

TwitterのOAuth2.0認可をSocialiteで実装しようとしたら401が返ってきた

Last updated at Posted at 2022-05-17

{"code":32,"message":"Could not authenticate you."}

Twitter の OAuth2.0 を用いた認可を Laravel の Socialite で実装しようとしたところ、出てきたエラーメッセージです。あなたが誰だか分からないって言われてますね。つまり、 Client ID などはちゃんと渡っているのにそれが符合しないというエラーだと思われます。
直感ではありましたが、これは OAuth1.0a で認可しようとしていて出ているエラーなのではと思いました。
じゃあ、ちゃんと OAuth2.0 を使うように指定しなければならないけれど、その方法が Laravel 公式をみてもいまいち分からない。
なので、ソースコードを読みに行きました。具体的にはこの辺

SocialiteManager.php
protected function createTwitterDriver()
{
    $config = $this->config->get('services.twitter');

    if (($config['oauth'] ?? null) === 2) {
        return $this->createTwitterOAuth2Driver();
    }

    return new TwitterProvider(
        $this->container->make('request'), new TwitterServer($this->formatConfig($config))
    );
}

fmfm、 config に services.twitter ってあって、その中に oauth って項目があってそれが 2 のときに createTwitterOAuth2Driver() という関数が呼び出されると。
じゃあ、こうすればいいんだな。

config/services.php に以下を追記

config/services.php
'twitter' => [
        'client_id' => env('TWITTER_CLIENT_ID'),
        'client_secret' => env('TWITTER_CLIENT_SECRET'),
        'redirect' => env('TWITTER_CALLBACK_URI'),
        'oauth' => 2,
]

ポイントはもちろん 'oauth' => 2 です。
これで無事 OAuth2.0 で認可ができるようになりました。

ちなみに権限設定は
https://github.com/laravel/socialite/blob/5.x/src/Two/TwitterProvider.php#L15

https://developer.twitter.com/en/docs/authentication/oauth-2-0/authorization-code
の Scopes を付き合わせれば多分大丈夫。

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1