Skip to content

Add GitHub state param #423

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/runtime/server/lib/oauth/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { H3Event } from 'h3'
import { eventHandler, getQuery, sendRedirect, createError } from 'h3'
import { withQuery } from 'ufo'
import { defu } from 'defu'
import { handleMissingConfiguration, handleAccessTokenErrorResponse, getOAuthRedirectURL, requestAccessToken } from '../utils'
import { getOAuthRedirectURL, handleAccessTokenErrorResponse, handleInvalidState, handleMissingConfiguration, handleState, requestAccessToken } from '../utils'
import { useRuntimeConfig } from '#imports'
import type { OAuthConfig } from '#auth-utils'

Expand Down Expand Up @@ -114,7 +114,7 @@ export function defineOAuthGitHubEventHandler({ config, onSuccess, onError }: OA
authorizationParams: {},
}) as OAuthGitHubConfig

const query = getQuery<{ code?: string, error?: string }>(event)
const query = getQuery<{ code?: string, error?: string, state?: string }>(event)

if (query.error) {
const error = createError({
Expand All @@ -131,6 +131,7 @@ export function defineOAuthGitHubEventHandler({ config, onSuccess, onError }: OA
}

const redirectURL = config.redirectURL || getOAuthRedirectURL(event)
const state = await handleState(event)

if (!query.code) {
config.scope = config.scope || []
Expand All @@ -144,11 +145,16 @@ export function defineOAuthGitHubEventHandler({ config, onSuccess, onError }: OA
client_id: config.clientId,
redirect_uri: redirectURL,
scope: config.scope.join(' '),
state,
...config.authorizationParams,
}),
)
}

if (query.state !== state) {
handleInvalidState(event, 'github', onError)
}

const tokens = await requestAccessToken(config.tokenURL as string, {
body: {
grant_type: 'authorization_code',
Expand Down