iTranslated by AI
Implementing Twitter Login (3-legged OAuth) with SvelteKit
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.
<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>
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.
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
{
oauth_token:'XXXXXXXXXXXXXXXXXX'
oauth_token_secret:'YYYYYYYYYYYYYYYYYYY'
screen_name:'asdfghjkl'
user_id:'1234567890'
}
Discussion
これはTwitterのバグなんじゃないかとずっと思ってるんですが、この流れの中でリクエストトークンシークレットの出番がありません。
ここでクエリから取得した
oauth_token,oauth_verifierのみでアクセストークン / アクセストークンシークレットを取得できるってことはoauth_token,oauth_verifierを用いてアクセストークン / アクセストークンシークレットを取得してDBに保持する = 第3者に悪意のあるユーザーのトークンが紐付けられるというCSRFが成り立ってしまいそうです。
本来は
getAccessToken()という関数がoAuthRequestToken.oauth_token_secretの値も必要とするべきなんだと思いますが、Twitterがそれなしでのリクエストを許可していることは変えられないので、CSRF対策としてコールバック時に
oAuthRequestToken.oauth_tokenの値をセッションに紐づけておくoauth_tokenの値が セッションと紐づけられている値と一致することを確認するという、OAuth 2.0における state パラメータと同様の実装をすることをお勧めします。
おっしゃっていることは理解できます。oauth_token が同一かどうかぐらいしかチェックする方法がないなという部分をその後の実装をしていて気にしていました。