iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌟

Implementing Twitter Login (3-legged OAuth) with SvelteKit

に公開2件

I am developing a feature to handle a user's Twitter access token and call the API on their behalf, which requires a 3-legged OAuth flow for the access token acquisition part.

Directory Structure

I set up the login process under routes/auth.

src/routes/auth/
├── callback.js
├── index.svelte
└── signin.js

0 directories, 3 files

/auth/

When a user accesses /auth/, it displays a sign-in button.

index.svelte
<a href="/auth/signin">
    <button>
        SIGN IN
    </button>
</a>

/auth/signin

Redirect to Twitter's authentication server.

Although Svelte has a redirect API for page components, it didn't seem suitable for use cases where the user directly hits an endpoint to trigger a redirect, so I chose to redirect using HTTP headers.

I referred to https://github.com/twitterdev/Twitter-API-v2-sample-code/ and https://github.com/twitterdev/twauth-web/ for handling connections with the Twitter server.

<ins>
Based on feedback, I added an oauth_token verification flow. This checks if the user returning in the callback is the same as the one who started the process.

SvelteKit's $app/stores doesn't work in endpoint contexts, so I'm planning to create my own mechanism for session persistence.
</ins>

signin.js
import ky from 'ky'
import crypto from 'crypto'
import OAuth from 'oauth-1.0a'
import qs from 'querystring'

const requestTokenURL = 'https://api.twitter.com/oauth/request_token';

const oauth = OAuth({
    consumer: {
        key: process.env.CONSUMER_KEY,
        secret: process.env.CONSUMER_SECRET,
    },
    signature_method: 'HMAC-SHA1',
    hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
});

async function requestToken() {
    const authHeader = oauth.toHeader(oauth.authorize({
        url: requestTokenURL,
        method: 'POST',
    }));

    const formData = new URLSearchParams();
    formData.set('oauth_callback', 'http://localhost:3000/auth/callback');
    
    const res = await ky.post(requestTokenURL, {
        body: formData.toString(),
        headers: {
            Authorization: authHeader["Authorization"]
        }
    });

    if (res.ok) {
        const body = await res.text()
        return qs.parse(body);
    } else {
        throw new Error('Cannot get an OAuth request token');
    }
}

export async function get(request) {
    const oAuthRequestToken = await requestToken()
    const authorizeURL = new URL('https://api.twitter.com/oauth/authorize');
    authorizeURL.searchParams.append('oauth_token', oAuthRequestToken.oauth_token)
    
    session(request).set('oauth_token', oAuthRequestToken.oauth_token)
    
    return {
        status: 302,
        headers: {
            'Location': authorizeURL.href
        }
    }
}

/auth/callback

The destination where the Twitter server redirects back to.

callback.js
const accessTokenURL = 'https://api.twitter.com/oauth/access_token';

async function getAccessToken(oauthToken, verifier) {
    const authHeader = oauth.toHeader(oauth.authorize({
        url: accessTokenURL,
        method: 'POST'
    }));

    const url = `${accessTokenURL}?oauth_verifier=${verifier}&oauth_token=${oauthToken}`
    const res = await ky.post(url, {
        headers: {
            Authorization: authHeader["Authorization"]
        }
    });

    if (res.ok) {
        const body = await res.text()
        return qs.parse(body);
    } else {
        throw new Error('Cannot get an OAuth request token');
    }
}

export async function get(request) {
    const oauthToken = request.query.get('oauth_token')
    if (session(request).get('oauth_token') !== oauthToken) {
        return {
            status: 403,
            body: 'token missmatch',
        }    
    }
    
    const verifier = request.query.get('oauth_verifier')
    const accessToken = await getAccessToken(oauthToken, verifier)
    
    // Example: Save to your service's database here
    // const user = getUser(request)
    // await user.token.update({
    //     data: accessToken,
    // })
    
    return {
        status: 302,
        headers: {
            'Location': '/',
        }
    }
}

Contents of the accessToken object

accessToken
{
    oauth_token:'XXXXXXXXXXXXXXXXXX'
    oauth_token_secret:'YYYYYYYYYYYYYYYYYYY'
    screen_name:'asdfghjkl'
    user_id:'1234567890'
}

Discussion

ritouritou

これはTwitterのバグなんじゃないかとずっと思ってるんですが、この流れの中でリクエストトークンシークレットの出番がありません。

export async function get(request) {
    const oauthToken = request.query.get('oauth_token')
    const verifier = request.query.get('oauth_verifier')
    const accessToken = await getAccessToken(oauthToken, verifier)

ここでクエリから取得した oauth_token, oauth_verifier のみでアクセストークン / アクセストークンシークレットを取得できるってことは

  1. 悪意のあるユーザーが自分が同意した後のコールバックURLを第3者に送る
  2. 第3者のブラウザ上で、悪意のあるユーザーの oauth_token, oauth_verifierを用いてアクセストークン / アクセストークンシークレットを取得してDBに保持する = 第3者に悪意のあるユーザーのトークンが紐付けられる

というCSRFが成り立ってしまいそうです。

本来は getAccessToken() という関数が oAuthRequestToken.oauth_token_secret の値も必要とするべきなんだと思いますが、Twitterがそれなしでのリクエストを許可していることは変えられないので、CSRF対策として

コールバック時に

  1. authorizeURL にリダイレクトする前に、oAuthRequestToken.oauth_token の値をセッションに紐づけておく
  2. クエリから取得した oauth_token の値が セッションと紐づけられている値と一致することを確認する

という、OAuth 2.0における state パラメータと同様の実装をすることをお勧めします。

laisolaiso

おっしゃっていることは理解できます。oauth_token が同一かどうかぐらいしかチェックする方法がないなという部分をその後の実装をしていて気にしていました。

1