문서
OAuth Server동의 화면

동의 화면

사용자가 서드파티 앱을 승인하는 여러분 애플리케이션의 페이지를 Next.js, Nuxt, SvelteKit, Remix로 만듭니다.

동의 화면은 OAuth 흐름에서 여러분이 직접 만드는 유일한 부분입니다. nulvless는 이를 렌더링하지 않으며, 이는 의도된 것입니다. 누군가 다른 회사에 자신의 계정 접근을 허용하는 순간, 그 사람이 보고 있어야 할 것은 여러분의 제품입니다.

동의 화면은 사이트 URL 안의, Console에서 설정한 인가 경로에 있습니다. 사용자는 쿼리 매개변수 하나와 함께 도착합니다.

https://yourapp.com/oauth/consent?authorization_id=auth_…

페이지가 해야 할 일

순서대로 네 가지입니다.

로그인 상태 확인

인가 엔드포인트는 세션을 대신해 동작합니다. 방문자가 로그아웃 상태라면 로그인 페이지로 보내고 authorization_id를 유지한 채 돌아오게 하세요. 이를 잃어버리면 사용자는 흐름 중간에서 갈 곳을 잃습니다.

요청 읽기

getAuthorization(id)는 클라이언트, 스코프, 그리고 이미 승인되었는지 여부를 반환합니다. 렌더링하는 모든 것은 여기서 가져옵니다. 클라이언트 이름을 자체 쿼리 문자열에서 읽지 마세요. 그 값은 클라이언트에서 온 것이 아니며, 이를 신뢰하면 동의 화면이 위조됩니다.

가능하면 화면 건너뛰기

autoApproved가 true이면, 이 사용자는 이 클라이언트에 바로 이 스코프들을 이미 허용했습니다. 렌더링하지 말고 승인한 뒤 리디렉션하세요. 이미 준 권한에 대해 동의 화면이 다시 나타나면 사람들이 읽지 않고 클릭하는 습관이 생깁니다.

autoApproved 없이 redirect가 있다면, 앱이 prompt=none을 보냈는데 사용자의 상호작용이 필요했다는 뜻입니다. 이때도 브라우저를 그곳으로 보내세요. 오류를 앱에 전달합니다.

응답을 기록하고 지시받은 곳으로 리디렉션

consent(id, 'approve' | 'deny')는 redirect.uri를 반환합니다. 브라우저를 그곳으로 보내세요. 이 URL을 직접 만들지 마세요. 코드와 state가 담겨 있으며, 직접 조립하면 이 값들을 잃어버리거나 유출하게 됩니다.

승인에 본인 확인이 필요한 경우

다음 두 경우에는 사용자가 본인임을 확인할 때까지 승인이 실패합니다.

  • protected_action_denied: 환경이 approve_oauth_apps를 Sudo 모드로 보호합니다.
  • login_required: 앱이 prompt=login을 보냈거나, 마지막 로그인보다 짧은 max_age를 보냈거나, 환경에서 항상 본인 확인이 켜져 있습니다.

login_required는 이 경우에 대해 OpenID Connect Core 1.0이 정의한 오류입니다. 둘 다 같은 방식으로 처리하세요. 코드를 보내고, 확인하고, 다시 승인합니다. 확인은 새로운 인증으로 간주되므로 auth_time도 갱신됩니다. 거부할 때는 묻지 않습니다.

const { error } = await nulvless.auth.oauth.consent(id, 'approve');

if (error?.code === 'protected_action_denied' || error?.code === 'login_required') {
  await nulvless.auth.sessions.sudo();
  await nulvless.auth.sessions.sudoVerify({ code: await askForCode() });
  const { data } = await nulvless.auth.oauth.consent(id, 'approve');
}

Next.js — App Router

서버 컴포넌트로 읽고, 서버 액션으로 응답합니다.

app/oauth/consent/page.tsx
import { redirect } from 'next/navigation';
import { createServerClient, forwardUserHeaders } from '@nulvless/nulvless-js';
import { headers } from 'next/headers';

export default async function ConsentPage({
  searchParams,
}: {
  searchParams: Promise<{ authorization_id?: string }>;
}) {
  const { authorization_id: id } = await searchParams;
  if (!id) redirect('/');

  const nulvless = createServerClient(process.env.NULVLESS_URL!, process.env.NULVLESS_KEY!);
  const { data, error } = await nulvless.auth.oauth.getAuthorization(id, {
    headers: forwardUserHeaders(new Request('https://x', { headers: await headers() })),
  });

  if (error) redirect(`/login?next=/oauth/consent?authorization_id=${id}`);
  if (data.autoApproved) redirect((await decide(id, 'approve')) as string);

  return (
    <main>
      <h1>{data.client.name} wants access to your account</h1>
      <ul>
        {data.scope.map((scope) => (
          <li key={scope}>{scopeLabel(scope)}</li>
        ))}
      </ul>
      <form action={approve}><button type="submit">Allow</button></form>
      <form action={deny}><button type="submit">Deny</button></form>
    </main>
  );

  async function approve() { 'use server'; redirect(await decide(id!, 'approve')); }
  async function deny() { 'use server'; redirect(await decide(id!, 'deny')); }
}

async function decide(id: string, action: 'approve' | 'deny') {
  'use server';
  const nulvless = createServerClient(process.env.NULVLESS_URL!, process.env.NULVLESS_KEY!);
  const { data } = await nulvless.auth.oauth.consent(id, action);
  return data.redirect.uri;
}

Nuxt

pages/oauth/consent.vue
<script setup lang="ts">
const route = useRoute();
const id = route.query.authorization_id as string;

if (!id) await navigateTo('/');

const { data, error } = await useAsyncData(`consent-${id}`, () =>
  $fetch(`/api/oauth/authorizations/${id}`),
);

if (error.value) {
  await navigateTo(`/login?next=${encodeURIComponent(route.fullPath)}`);
} else if (data.value?.autoApproved) {
  await decide('approve');
}

async function decide(action: 'approve' | 'deny') {
  const result = await $fetch<{ redirect: { uri: string } }>(
    `/api/oauth/authorizations/${id}/consent`,
    { method: 'POST', body: { action } },
  );

  await navigateTo(result.redirect.uri, { external: true });
}
</script>

<template>
  <main v-if="data">
    <h1>{{ data.client.name }} wants access to your account</h1>
    <ul>
      <li v-for="scope in data.scope" :key="scope">{{ scopeLabel(scope) }}</li>
    </ul>
    <button @click="decide('approve')">Allow</button>
    <button @click="decide('deny')">Deny</button>
  </main>
</template>

external: true가 중요합니다

navigateTo는 기본적으로 클라이언트 측 라우팅을 사용합니다. 리디렉션 URI는 서드파티 앱의 것이므로 여러분의 애플리케이션을 벗어나야 합니다. external: true가 없으면 Nuxt가 이를 자체 라우트로 해석하려 하고 흐름이 막다른 길에 빠집니다.

SvelteKit

로더로 읽고, 폼 액션으로 응답합니다.

src/routes/oauth/consent/+page.server.ts
import { redirect, error } from '@sveltejs/kit';
import { nulvless } from '$lib/server/nulvless';

export async function load({ url, locals }) {
  const id = url.searchParams.get('authorization_id');
  if (!id) redirect(303, '/');
  if (!locals.session) redirect(303, `/login?next=${encodeURIComponent(url.pathname + url.search)}`);

  const { data, error: failure } = await nulvless.auth.oauth.getAuthorization(id);
  if (failure) error(400, failure.message);

  if (data.autoApproved) {
    const { data: result } = await nulvless.auth.oauth.consent(id, 'approve');
    redirect(303, result.redirect.uri);
  }

  return { id, client: data.client, scope: data.scope };
}

export const actions = {
  decide: async ({ request, url }) => {
    const id = url.searchParams.get('authorization_id')!;
    const action = (await request.formData()).get('action') as 'approve' | 'deny';

    const { data } = await nulvless.auth.oauth.consent(id, action);
    redirect(303, data.redirect.uri);
  },
};
src/routes/oauth/consent/+page.svelte
<script lang="ts">
  let { data } = $props();
</script>

<main>
  <h1>{data.client.name} wants access to your account</h1>
  <ul>
    {#each data.scope as scope}<li>{scopeLabel(scope)}</li>{/each}
  </ul>
  <form method="POST" action="?/decide">
    <button name="action" value="approve">Allow</button>
    <button name="action" value="deny">Deny</button>
  </form>
</main>

Remix / React Router

app/routes/oauth.consent.tsx
import { redirect, Form, useLoaderData } from 'react-router';
import { nulvless } from '~/lib/nulvless.server';

export async function loader({ request }: { request: Request }) {
  const url = new URL(request.url);
  const id = url.searchParams.get('authorization_id');
  if (!id) throw redirect('/');

  const { data, error } = await nulvless.auth.oauth.getAuthorization(id);
  if (error) throw redirect(`/login?next=${encodeURIComponent(url.pathname + url.search)}`);

  if (data.autoApproved) {
    const { data: result } = await nulvless.auth.oauth.consent(id, 'approve');
    throw redirect(result.redirect.uri);
  }

  return { id, client: data.client, scope: data.scope };
}

export async function action({ request }: { request: Request }) {
  const form = await request.formData();
  const id = new URL(request.url).searchParams.get('authorization_id')!;

  const { data } = await nulvless.auth.oauth.consent(
    id,
    form.get('action') as 'approve' | 'deny',
  );

  return redirect(data.redirect.uri);
}

export default function Consent() {
  const { client, scope } = useLoaderData<typeof loader>();

  return (
    <main>
      <h1>{client.name} wants access to your account</h1>
      <ul>{scope.map((s) => <li key={s}>{scopeLabel(s)}</li>)}</ul>
      <Form method="post">
        <button name="action" value="approve">Allow</button>
        <button name="action" value="deny">Deny</button>
      </Form>
    </main>
  );
}

화면의 문구 작성하기

코드는 쉬운 절반입니다. 페이지가 무엇을 말하는지가 동의가 의미를 갖는지를 결정합니다.

요청이 아니라 앱 이름을 말하세요. "Acme Analytics가 계정에 대한 접근을 요청합니다"는 누가 요청하는지 알려 줍니다. "애플리케이션 승인"은 아무것도 알려 주지 않습니다.

스코프를 결과로 풀어 쓰세요. profile은 문장이 아니라 프로토콜 토큰입니다. "이름과 사진 보기"가 사용자가 실제로 동의하는 내용입니다.

스코프작성할 문구
openid본인 확인
email이메일 주소 보기
profile이름과 사진 보기
phone전화번호 보기

받은 로고와 URL을 보여 주세요. client.logoUri와 client.uri에서 가져옵니다. 사용자가 아는 앱을 알아보고, 모르는 앱을 알아차리는 데 도움이 됩니다.

"거부"를 진짜 버튼으로 만드세요. 눈에 띄는 동작이 하나뿐인 동의 화면은 동의가 아니라 과속 방지턱일 뿐입니다. 거부도 정당한 답이며, 그렇게 보여야 합니다.

누가 로그인했는지 알려 주세요. 두 계정에 로그인한 사람에게 어느 계정을 연결하려는지 알려 주는 것은 여러분의 페이지뿐입니다.

쿼리 문자열의 값을 렌더링하지 마세요

신뢰해야 할 매개변수는 authorization_id뿐이며, 그것도 조회 키로만 사용합니다. 표시하는 모든 이름, 로고, 스코프는 getAuthorization에서 가져와야 합니다. 그 응답은 여러분의 프로젝트에서 온 것입니다. URL의 값은 사용자를 보낸 쪽, 즉 보증 대상인 바로 그 당사자에게서 온 것입니다.

이 페이지의 내용