LoginSignup
2
2

NextAuthでX(Twitter)Api Oauth2.0が使いたい!

Posted at

NextAuth.jsとは

NextAuth.jsとはNext.js向けに作成されたJavascriptライブラリになります。
これを導入することでGoogleでログインやX(Twitter)でログインなどの認証処理が簡単なコードを書くだけで実現できます。

X(Twitter)でログインを設定する

X(Twitter)でログインをする場合、OAuth認証※を利用します。

※認可プロトコルの一種で限定的なアクセス権限を別のサービスに移譲できます。

2通りの設定があります。

  1. OAuth1.0aを利用
  2. OAuth2.0を利用

OAuth1.0a(OAuth1.0)とOAuth2.0の違い

主な違いとしては以下になります。

  • 処理の複雑さ(OAuth2.0の方がシンプル)
  • アクセストークンの期限(OAuth2.0の方が短い)

NextAuth.jsの設定

以下を参考

Twitter OAuth1.0aを使う場合

src/pages/api/auth/[...nextauth].ts
export const authOptions: NextAuthOptions = {
  providers: [
    // Twitter oauth1.0aを使う場合
    TwitterProvider({
      clientId: serverRuntimeConfig.twitterClientId,
      clientSecret: serverRuntimeConfig.twitterClientScret,
    }),
  ],

Twitter OAuth2.0を使う場合

src/pages/api/auth/[...nextauth].ts
const TWITTER_AUTHORIZATION = {
  url: 'https://twitter.com/i/oauth2/authorize',
  params: {
    // 以下のScopesに書かれいるもの設定
    // https://developer.twitter.com/en/docs/authentication/oauth-2-0/authorization-code
    scope: 'users.read tweet.read offline.access',
  },
}
export const authOptions: NextAuthOptions = {
  providers: [
    TwitterProvider({
       clientId: serverRuntimeConfig.twitterClientId,
       clientSecret: serverRuntimeConfig.twitterClientScret,
       version: '2.0',
       authorization: TWITTER_AUTHORIZATION,
    }),
  ],

問題点

OAuth2.0を使った場合、認可URLが
https://twitter.com/i/oauth2/authorize?...
となっているためスマホなどでネイティブアプリが起動してしまい、
アプリブラウザで認可同意画面が開いてしまう現象が発生します。

今現在は解決策が見つからないためサービスによってはOAuth1.0aを利用せざるを得ない場合があります。

2
2
0

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
2