SuperTokens passwordless認証を次のように統合します.js
簡単な紹介
Authentication
アプリケーションのユーザーIDを検証するメカニズムです.UserIDとパスワードを使用してユーザーの認証は、多くのアプリケーションで使用する最も一般的なメカニズムです.しかし、他にも有名なアプローチがある.我々は、社会的ログイン、ワンタイムパスワード(OTP)、または直接認証を支援する魔法のリンクを使用してユーザーを認証することができます.SuperTokens あなたのウェブアプリケーションのための認証メカニズムのすべてのこれらの形に役立つオープンソースの、非常にカスタマイズされたユーザーAuthプロバイダーフレームワークです.Nodejs、Golang、PythonとReactJSとフロントエンド側のようなバックエンドフレームワークと統合するのは簡単です.
Next.js 急速なWebアプリケーションを構築するための一般的な反応フレームワークです.本稿では、スーパートークン認証機構のパワーを次のように統合する方法を学びます.JSアプリケーション.我々は、に焦点を当てる
passwordless
認証、しかし、他のレシピは、社会的なログインまたはユーザーID/パスワードを使用するようになります.今日何を建てていますか.
我々は、シンプルだが効果的な次から始まります.JSアプリとスーパートークンの電源を統合します.アプリは呼ばれます
Retell
, これは世界中で有名な人々の有名な引用符を示しています.お気に入りのコードエディタを開き、この記事に従ってください.建物を楽しむ.任意の時点で、ソースコードを参照する場合は、ここで見つけることができます.
atapas / quotes
SuperTokensのPasswrodless AuthとNextJSの統合を実証するプロジェクト
Aをください⭐ あなたが仕事が好きならばrepoに.それは私を動機づける.
設定
Retell
プロジェクトUIこの記事は、あなたが反応の基本的な理解を持っていると仮定します.JSと次のことができます.ソースコード.これらの手順を実行してください
Retell
ローカルのプロジェクトユーザインタフェース npm install
# or
yarn
npm run dev
# or
yarn dev
今すぐURLを使用してアプリケーションにアクセスhttp://localhost:3000 引用符を正常にレンダリングを参照してください.また、
quotes
URLを使用するAPIhttp://localhost:3000/api/quotes おめでとう!あなたはUIを実行している.私たちはsuperTokens passwordless authを統合しましょう.
Supertokens Authの設定
SuperTokens
パスワードなしAuthレシピは、OTP(ワンタイムパスワード)と魔法のリンクを使用して認証することができます.このAuth Typeを次のように設定します.いくつかの手順でJSアプリ.yarn add supertokens-auth-react supertokens-node dotenv nodemailer
フロントエンドとバックエンドの設定
クリエイトア
.env.local
次のコンテンツをプロジェクトのルートでファイルします.NEXT_PUBLIC_NODEMAILER_USER=<YOUR_GMAIL_ID>
NEXT_PUBLIC_NODEMAILER_PASSWORD=<YOUR_GMAIL_PASSWORD>
NEXT_PUBLIC_APP_URL=http://localhost:3000
Important Note: The Gmail id and password is required to send OTP and Magic Link over email. Please do not use your personal Gmail id for this purpose. You can create a fake Gmail id and lower the security settings to use it for testing purposes.
クリエイトア
config
プロジェクトのルートのフォルダ.今すぐ作成appInfo.js
インサイドconfig
次のコンテンツを含むフォルダconst port = process.env.APP_PORT || 3000
const apiBasePath = '/api/auth/'
export const websiteDomain =
process.env.APP_URL ||
process.env.NEXT_PUBLIC_APP_URL ||
`http://localhost:${port}`
export const appInfo = {
appName: 'Retell',
websiteDomain,
apiDomain: websiteDomain,
apiBasePath,
}
The appInfo.js
ファイルにはフロントエンドとバックエンドの設定のための変数を指定する特別なオブジェクトが含まれます.してくださいappInfo
オブジェクトfrom here .次に、
frontendConfig.js
ファイルの内部config
次のコンテンツを含むフォルダimport PasswordlessReact from "supertokens-auth-react/recipe/passwordless";
import SessionReact from "supertokens-auth-react/recipe/session";
import { appInfo } from "./appInfo";
export const frontendConfig = () => {
return {
appInfo,
recipeList: [
PasswordlessReact.init({
contactMethod: "EMAIL_OR_PHONE",
}),
SessionReact.init(),
],
};
};
ここでSuperTokensのフロントエンドSDKの設定を提供する機能を作成します.その後、この関数の使い方を見ます.ご連絡方法はEMAIL_OR_PHONE
. これは、ユーザーがログインするように指定されるメールや電話番号にOTPと魔法のリンクを送信することによってpasswordless認証が発生することを意味します.ではバックエンドの設定を作成しましょう.ファイルを作成してください
backendConfig.js
インサイドconfig
次のコンテンツを含むフォルダrequire("dotenv").config();
import Session from "supertokens-auth-react/recipe/session";
import PasswordlessNode from "supertokens-node/recipe/passwordless";
import SessionNode from "supertokens-node/recipe/session";
import { appInfo } from "./appInfo";
let { getEmailBody } = require("../util/mailer");
export const backendConfig = () => {
const nodemailer = require('nodemailer');
const mailTransporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
user: process.env.NEXT_PUBLIC_NODEMAILER_USER,
pass: process.env.NEXT_PUBLIC_NODEMAILER_PASSWORD,
},
});
return {
framework: "express",
supertokens: {
connectionURI: "https://try.supertokens.com",
// apiKey: "IF YOU HAVE AN API KEY FOR THE CORE, ADD IT HERE",
},
appInfo,
recipeList: [
PasswordlessNode.init({
flowType: "USER_INPUT_CODE_AND_MAGIC_LINK",
contactMethod: "EMAIL_OR_PHONE",
createAndSendCustomEmail: async (input, context) => {
try{
let htmlBody = getEmailBody(
appInfo.appName,
Math.ceil(input.codeLifetime / 1000),
input.urlWithLinkCode,
input.userInputCode,
input.email
);
await mailTransporter.sendMail({
html: htmlBody,
to: input.email,
from: `Team Supertokens <${appInfo.appName}>`,
sender: process.env.NEXT_PUBLIC_NODEMAILER_USER,
subject: `Login to ${appInfo.appName}`,
});
} catch (err) {
console.log(err);
}
},
createAndSendCustomTextMessage: async (input, context) => {
// Creating a Twilio account and set it up.
},
}),
SessionNode.init(),
],
isInServerlessEnv: true,
};
};
私たちはtry.supertokens.com
としてconnectionURI
上記の値.URIトライに注意してください.スーパートークンCOMはデモ目的です.あなた自身のコアを設定し、上記のコアアドレスを置き換える必要があります.つの方法で独自のコアを設定できます.
By self-hosting SuperTokens
: SuperTokensコアを自分のデータベースでセルフホストできます.MySQL or PostgreSQL ). あなたはいずれかのホストをmanually installing SuperTokens またはdocker . By using the managed service option
: マネージサービスでSuperTokensコアを設定するにはcreate a free account でログインします.次に、ダッシュボードから新しいアプリケーションを作成します.一度完了すると、アプリケーションの詳細ページからConnectionURIとAPIキーを見つける.createAndSendCustomEmail
: これは、環境変数からGmailの資格情報を使用して電子メールベースの配信方法です.注意してください私たちはgetEmailBody()
電子メールメッセージをフォーマットする方法.util
プロジェクトフォルダのルートで.ではファイル名mailer.js
それはgetEmailBody()
メソッド.Here is a sample implementation メーラーのjsファイル.あなたはペースト全体のコンテンツをコピーすることができます.createAndSendCustomTextMessage
: SMSベースの配信方法です.を作成することができますTwilio アカウントといくつかの簡単な手順でそれを設定します.その例を見つけることができますfrom here . ここでは、フロントエンドのinit関数を
_app.js
ファイル.どうぞお開きください_app.js
ファイル下にpages
フォルダーを次のように置き換えます.import React from 'react'
import SuperTokensReact from 'supertokens-auth-react'
import { frontendConfig } from '../config/frontendConfig'
import '../styles/globals.css'
if (typeof window !== 'undefined') {
// we only want to call this init function on the frontend, so
// we check typeof window !== 'undefined'
SuperTokensReact.init(frontendConfig())
}
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
export default MyApp
したがって、今ではすべての設定で行われます.ログインユーザーインターフェイスを表示しましょう.ログインUIを表示する
を作成してください
auth
フォルダ内のpages
フォルダ.今すぐ作成[[...path]].js
ファイルの内部auth/pages
次のコンテンツを含むフォルダimport dynamic from 'next/dynamic'
import React, { useEffect } from 'react'
import SuperTokens from 'supertokens-auth-react'
import { redirectToAuth } from 'supertokens-auth-react/recipe/passwordless'
const SuperTokensComponentNoSSR = dynamic(
new Promise((res) => res(SuperTokens.getRoutingComponent)),
{ ssr: false }
)
export default function Auth() {
// if the user visits a page that is not handled by us (like /auth/random),
// then we redirect them back to the auth page.
useEffect(() => {
if (SuperTokens.canHandleRoute() === false) {
redirectToAuth()
}
}, [])
return (
<SuperTokensComponentNoSSR />
)
}
それは私たちのauthコンポーネントです.さあ、テストしましょう.ブラウザタブを開き、アプリケーションのアクセス/auth
URLhttp://localhost:3000/auth . この段階でログインユーザーインターフェイスが表示されます.メインアプリケーションのページ(localhost:3000)と引用API(localhost:3000/API/引用符)はまだAuthで保護されていません.一人ずつやりましょう.
Auth APIを追加する
今、私たちはAuthのすべてのバックエンドAPIを追加します
/api/auth
. を作成してくださいauth
フォルダ内のpages/api/
フォルダ.ではファイルを作る[[...path]].js
を返します.require("dotenv").config();
import supertokens from 'supertokens-node';
import { middleware } from 'supertokens-node/framework/express';
import { superTokensNextWrapper } from 'supertokens-node/nextjs';
import { backendConfig } from '../../../config/backendConfig';
supertokens.init(backendConfig())
export default async function superTokens(req, res) {
await superTokensNextWrapper(
async (next) => {
await middleware()(req, res, next)
},
req,
res
)
if (!res.writableEnded) {
res.status(404).send('Not found')
}
}
The [[...path]].js
ファイルが露出したミドルウェアを使うsupertokens-node
, サインやサインアップのようなすべてのAPIを公開します.今すぐ更新
quotes
APIは、アクセス許可を持っている.の内容を更新してくださいquotes.js
以下の内容を持つファイルimport supertokens from 'supertokens-node';
import { superTokensNextWrapper } from 'supertokens-node/nextjs';
import { verifySession } from 'supertokens-node/recipe/session/framework/express';
import { backendConfig } from '../../config/backendConfig';
import quoteList from '../../data/quotes.json';
supertokens.init(backendConfig())
export default async function quotes(req, res) {
await superTokensNextWrapper(
async (next) => {
return await verifySession()(req, res, next)
},
req,
res
)
return res.json(quoteList.quotes)
}
今すぐ引用符APIにアクセスします.http://localhost:3000/api/quotes . 不正なエラーが表示されます.心配するな.我々は現在、ワークフロー全体を修正します.
保護ルート
それで、すべてを働かせるために、ルートを保護しましょう.どうぞお開きください
index.js
ファイル下にpages
フォルダーを次のコンテンツに置き換えます.import dynamic from 'next/dynamic';
import Head from 'next/head';
import React from 'react';
import Passwordless from "supertokens-auth-react/recipe/passwordless";
import supertokensNode from 'supertokens-node';
import Session from 'supertokens-node/recipe/session';
import Footer from '../components/Footer';
import Header from '../components/Header';
import QuoteList from '../components/QuoteList';
import styles from '../styles/Home.module.css';
const PasswordlessAuthNoSSR = dynamic(
new Promise((res) =>
res(Passwordless.PasswordlessAuth)
),
{ ssr: false }
)
export default function Home(props) {
return (
<PasswordlessAuthNoSSR>
<ProtectedPage />
</PasswordlessAuthNoSSR>
)
}
function ProtectedPage({ userId }) {
async function logoutClicked() {
await Passwordless.signOut()
Passwordless.redirectToAuth()
}
return (
<div className={styles.container}>
<Head>
<title>Retell</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header />
<main className={styles.main}>
<QuoteList />
</main>
<Footer />
</div>
)
}
それです.あなたはアプリや引用符APIにアクセスし、ログインページは両方を保護します.あなたは、OTPを取得し、引用符にアクセスする前に自分自身を承認するあなたの電話番号や電子メールのIDを提供する必要があります.あなたのための仕事
大丈夫、あなたのための小さな仕事.ログアウト機能を実装できますか?に
index.js
ページには、関数logoutClicked()
. 方法を誰かがクリックするときにメソッドを呼び出すSign Out
ヘッダーのリンク?試してみてください!もう一度、ソースコード全体が私のgithubにあります.https://github.com/atapas/quotes . あなたがこの記事またはエラーをワークフローを実装する際にどんな問題にでも直面するならばDiscord .
終わる前に.
もうこれだけです.私はあなたがこの記事は洞察力を発見願っています.
私は知識を共有します.
Reference
この問題について(SuperTokens passwordless認証を次のように統合します.js), 我々は、より多くの情報をここで見つけました https://dev.to/atapas/integrate-supertokens-passwordless-authentication-with-nextjs-3j7jテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol