Unverified Commit e875dded authored by Balázs Orbán's avatar Balázs Orbán Committed by GitHub

chore(examples): add Authsignal passwordless example (#41079)

Lands #39048 with lint fixes. Needed to open a new PR, because GitHub
does not allow maintainers to edit organization forks.

https://github.com/orgs/community/discussions/5634

Closes #39048

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
Co-authored-by: 's avatarChris Fisher <chris.i.fisher@gmail.com>
parent c988b99c
AUTHSIGNAL_SECRET=
SESSION_TOKEN_SECRET=
REDIRECT_URL=http://localhost:3000/api/finalize-login
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
\ No newline at end of file
# Authsignal Passwordless Login Example
This example shows how to integrate Authsignal with Next.js in order to implement passwordless login using email magic links and server-side redirects.
The login session is managed using cookies. Session data is encrypted using [@hapi/iron](https://hapi.dev/family/iron).
A live version of this example can be found [here](https://authsignal-next-passwordless-example.vercel.app).
## Deploy your own
Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/authsignal-passwordless&project-name=authsignal-passwordless&repository-name=authsignal-passwordless)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```bash
npx create-next-app --example authsignal-passwordless authsignal-passwordless-app
# or
yarn create next-app --example authsignal-passwordless authsignal-passwordless-app
# or
pnpm create next-app --example authsignal-passwordless authsignal-passwordless-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
## Configuration
Log in to the [Authsignal Portal](https://portal.authsignal.com) and [enable email magic links for your tenant](https://portal.authsignal.com/organisations/tenants/authenticators).
Copy the .env.local.example file to .env.local:
```
cp .env.local.example .env.local
```
Set `AUTHSIGNAL_SECRET` as your [Authsignal secret key](https://portal.authsignal.com/organisations/tenants/api).
The `SESSION_TOKEN_SECRET` is used to encrypt the session cookie. Set it to a random string of 32 characters.
## Notes
To learn more about Authsignal take a look at the [API Documentation](https://docs.authsignal.com/).
.header {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #1d1d1d;
width: 100%;
}
.header button {
cursor: pointer;
font-size: 13px;
font-weight: 500;
line-height: 1;
border: none;
background: none;
color: #fff;
padding: 15px;
transition: background-color 0.15s, color 0.15s;
}
.user {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
flex-grow: 1;
}
.label {
font-size: 12px;
margin-bottom: 5px;
}
.logo {
font-size: 18px;
margin: 15px;
color: #fff;
}
import { useRouter } from 'next/router'
import { User } from '../lib'
import styles from './dashboard.module.css'
interface Props {
user: User
}
export const Dashboard = ({ user }: Props) => {
const router = useRouter()
const logout = async () => {
await fetch('/api/logout', {
method: 'POST',
credentials: 'same-origin',
})
router.push('/')
}
return (
<>
<header className={styles.header}>
<div className={styles.logo}>My Example App</div>
<button onClick={() => logout()}>Log out</button>
</header>
<div className={styles.user}>
<div>
<div className={styles.label}>Logged in as:</div>
<div>{user.email}</div>
</div>
</div>
</>
)
}
export * from './dashboard'
export * from './layout'
export * from './login'
import Head from 'next/head'
type Props = {
children: React.ReactNode
}
export const Layout = (props: Props) => (
<>
<Head>
<title>Authsignal Passwordless Example</title>
<link rel="icon" href="/favicon.ico" />
</Head>
{props.children}
</>
)
.login {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
flex-grow: 1;
}
.login form {
display: flex;
flex-direction: column;
min-width: 300px;
}
.login label {
font-size: 12px;
margin-bottom: 5px;
color: #ababab;
}
.login input {
outline: none;
font-family: inherit;
font-size: 13px;
font-weight: 400;
background-color: #fff;
border-radius: 6px;
color: #1d1d1d;
border: 1px solid #e8e8e8;
padding: 0 15px;
margin: 0 0 15px 0;
height: 40px;
}
.login button {
cursor: pointer;
font-size: 13px;
font-weight: 500;
line-height: 1;
border-radius: 6px;
border: none;
background-color: #1d1d1d;
color: #fff;
padding: 0 15px;
height: 40px;
transition: background-color 0.15s, color 0.15s;
}
.login button:hover:not(:active) {
background-color: #282828;
}
.title {
font-size: 24px;
margin-bottom: 30px;
font-weight: 400;
}
import styles from './login.module.css'
export const Login = () => (
<main className={styles.login}>
<h1 className={styles.title}>My Example App</h1>
<form method="POST" action="/api/login">
<label htmlFor="email">Email</label>
<input id="email" type="email" name="email" required />
<button type="submit">Log in / Sign up</button>
</form>
</main>
)
import { Authsignal } from '@authsignal/node'
const secret = process.env.AUTHSIGNAL_SECRET!
export const authsignal = new Authsignal({ secret })
import Iron from '@hapi/iron'
import { parse, serialize } from 'cookie'
export const COOKIE_NAME = 'session_token'
const TOKEN_SECRET = process.env.SESSION_TOKEN_SECRET!
export async function createCookieForSession(user: User) {
// Make login session valid for 8 hours
const maxAge = 60 * 60 * 8
const expires = new Date()
expires.setSeconds(expires.getSeconds() + maxAge)
const sessionData: SessionData = { user, expiresAt: expires.toString() }
const sessionToken = await Iron.seal(sessionData, TOKEN_SECRET, Iron.defaults)
const cookie = serialize(COOKIE_NAME, sessionToken, {
maxAge,
expires,
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
path: '/',
sameSite: 'lax',
})
return cookie
}
export async function getSessionFromCookie(cookie: string | undefined) {
const cookies = parse(cookie ?? '')
const sessionToken = cookies[COOKIE_NAME]
if (!sessionToken) {
return undefined
}
const sessionData: SessionData = await Iron.unseal(
sessionToken,
TOKEN_SECRET,
Iron.defaults
)
return sessionData
}
export interface SessionData {
user: User
expiresAt: string
}
export interface User {
userId: string
email?: string
}
export * from './authsignal'
export * from './cookies'
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
}
module.exports = nextConfig
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"@authsignal/node": "^0.0.29",
"@hapi/iron": "^7.0.0",
"cookie": "^0.5.0",
"next": "latest",
"react": "18.2.0",
"react-dom": "18.2.0"
},
"devDependencies": {
"@types/cookie": "^0.5.1",
"@types/node": "18.0.3",
"@types/react": "18.0.15",
"@types/react-dom": "18.0.6",
"typescript": "4.7.4"
}
}
import type { AppProps } from 'next/app'
import './globals.css'
export default function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} />
}
import { NextApiRequest, NextApiResponse } from 'next'
import { authsignal, createCookieForSession } from '../../lib'
// This route handles the redirect back from the Authsignal Prebuilt MFA page
export default async function finalizeLogin(
req: NextApiRequest,
res: NextApiResponse
) {
// Only GET requests since we are handling redirects
if (req.method !== 'GET') {
return res.status(405).send({ message: 'Only GET requests allowed' })
}
const token = req.query.token as string
// This step uses your secret key to validate the token returned via the redirect
// It makes an authenticated call to Authsignal to check if the magic link challenge succeeded
const { success, user } = await authsignal.validateChallenge({ token })
if (success) {
const cookie = await createCookieForSession(user)
res.setHeader('Set-Cookie', cookie)
}
res.redirect('/')
}
import { NextApiRequest, NextApiResponse } from 'next'
import { authsignal } from '../../lib'
export default async function login(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405).send({ message: 'Only POST requests allowed' })
}
const { email } = req.body
const { url } = await authsignal.loginWithEmail({ email, redirectUrl })
res.redirect(303, url)
}
const redirectUrl =
process.env.REDIRECT_URL ?? 'http://localhost:3000/api/finalize-login'
import { NextApiRequest, NextApiResponse } from 'next'
import { serialize } from 'cookie'
import { COOKIE_NAME } from '../../lib'
export default async function logout(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'POST') {
return res.status(405).send({ message: 'Only POST requests allowed' })
}
const cookie = serialize(COOKIE_NAME, '', { maxAge: -1, path: '/' })
res.setHeader('Set-Cookie', cookie)
res.send({ success: true })
}
*,
*::before,
*::after {
box-sizing: border-box;
}
html,
body {
height: 100%;
min-height: 100%;
}
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
'Helvetica Neue', Arial, Noto Sans, sans-serif, 'Apple Color Emoji',
'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
}
#__next {
display: flex;
flex-direction: column;
min-height: 100%;
}
import { GetServerSideProps } from 'next'
import { Dashboard, Layout, Login } from '../components'
import { getSessionFromCookie, User } from '../lib'
interface Props {
user: User | null
}
export const getServerSideProps: GetServerSideProps<Props> = async ({
req,
}) => {
const session = await getSessionFromCookie(req.headers.cookie)
if (session && new Date(session.expiresAt) > new Date()) {
return { props: { user: session.user } }
} else {
return { props: { user: null } }
}
}
export default function HomePage({ user }: Props) {
return <Layout>{user ? <Dashboard user={user} /> : <Login />}</Layout>
}
<svg width="283" height="64" viewBox="0 0 283 64" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M141.04 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.46 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM248.72 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.45 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM200.24 34c0 6 3.92 10 10 10 4.12 0 7.21-1.87 8.8-4.92l7.68 4.43c-3.18 5.3-9.14 8.49-16.48 8.49-11.05 0-19-7.2-19-18s7.96-18 19-18c7.34 0 13.29 3.19 16.48 8.49l-7.68 4.43c-1.59-3.05-4.68-4.92-8.8-4.92-6.07 0-10 4-10 10zm82.48-29v46h-9V5h9zM36.95 0L73.9 64H0L36.95 0zm92.38 5l-27.71 48L73.91 5H84.3l17.32 30 17.32-30h10.39zm58.91 12v9.69c-1-.29-2.06-.49-3.2-.49-5.81 0-10 4-10 10V51h-9V17h9v9.2c0-5.08 5.91-9.2 13.2-9.2z" fill="#000"/>
</svg>
\ No newline at end of file
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment