Open18

Cognito + Next.jsで、Amplifyなしで認証を実現する

巳波みなと巳波みなと

必須条件

  • Amplify使わない
  • バックエンドは別で立てる
  • Next.jsのAPI Routeも使わない
  • できるだけ認証はフロントで完結させたい

前提条件

  • Next.jsはPages Router
  • CognitoはID/PW認証はせず、OIDC(LINE)の認証を使う
巳波みなと巳波みなと

前は割とすんなりできたけど、なんかいろいろ変わってるっぽい

巳波みなと巳波みなと

NextjsのAPI Routeを使いたくないので、もちろんAuth.jsも使わない

巳波みなと巳波みなと

https://www.npmjs.com/package/amazon-cognito-identity-js

Developer Note: Please Update to Amplify v6
We recommend using the Amplify JavaScript library's Auth features in place of the Amazon Cognito Identity SDK. The Amplify JavaScript library offers a modern, fully-typed, and performant experience for Auth use cases with tree-shaking built-in for bundle size reduction.

Amplify v6がrecommendされてる

巳波みなと巳波みなと

公式としては aws-amplifyと @aws-amplify/ui-reactを使っていろいろやるのがセオリーっぽい

巳波みなと巳波みなと

ドキュメントの節々からAmplifyを使わせたいという雰囲気を感じる

巳波みなと巳波みなと

Is there a way to upgrade an existing Amplify project from Gen 1 to Gen 2?

We are still actively developing migration tooling to aid in transitioning your project from Gen 1 to Gen 2. Until then, we recommend you continue working with your Gen 1 Amplify project. We’ve put together a Gen 1 vs. Gen 2 feature support matrix here. We remain committed to supporting both Gen 1 and Gen 2 for the foreseeable future. For new projects, we recommend adopting Gen 2 to take advantage of its enhanced capabilities. Meanwhile, customers on Gen 1 will continue to receive support for high-priority bugs and essential security updates.

https://docs.amplify.aws/javascript/how-amplify-works/faq/

まだ移行準備中っぽい

巳波みなと巳波みなと

新しくアプリケーション作る場合はGen2使えとは言われている

巳波みなと巳波みなと
        await signInWithRedirect({
            provider: {
                custom: "LINE",
            },
        });

これでいけるっぽい

巳波みなと巳波みなと
import { Button } from "@nextui-org/react";
import { signInWithRedirect, getCurrentUser } from "aws-amplify/auth";

export default function Home() {
    const handleSignIn = async () => {
        await signInWithRedirect({
            provider: {
                custom: "LINE",
            },
        });
    };

    const getUser = async () => {
        const user = await getCurrentUser();

        console.log(user);
    };

    return (
        <>
            <Button onPress={() => handleSignIn()}>ログイン</Button>
            <Button onPress={() => getUser()}>ユーザー取得</Button>
        </>
    );
}
巳波みなと巳波みなと

redirect_uriは最後に/を含める or 含めないまで評価されるので、そこもCognitoとフロントで合わせる

巳波みなと巳波みなと

The Authenticator component is automatically configured based on the outputs generated from your backend. To learn more about the Authenticator and how to customize its appearance, visit the Amplify UI documentation.

Conversely, you can bring your own UI and leverage the library from aws-amplify to handle authentication flows manually.

https://docs.amplify.aws/react/build-a-backend/auth/connect-your-frontend/using-the-authenticator/

aws-amplify/ui-reactは全然必須ではなさそう