Skip to content
Merged
Show file tree
Hide file tree
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
4 changes: 2 additions & 2 deletions Sample-01/.env.local.example
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
AUTH0_SECRET=replace-with-your-own-secret-generated-with-openssl
AUTH0_BASE_URL=http://localhost:3000
AUTH0_ISSUER_BASE_URL='https://{DOMAIN}'
APP_BASE_URL=http://localhost:3000
AUTH0_DOMAIN='{DOMAIN}'
AUTH0_CLIENT_ID='{CLIENT_ID}'
AUTH0_CLIENT_SECRET='{CLIENT_SECRET}'
AUTH0_AUDIENCE=
Expand Down
6 changes: 3 additions & 3 deletions Sample-01/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ To do this, first copy `.env.local.example` into a new file in the same folder c
# A long secret value used to encrypt the session cookie
AUTH0_SECRET='LONG_RANDOM_VALUE'
# The base url of your application
AUTH0_BASE_URL='http://localhost:3000'
# The url of your Auth0 tenant domain
AUTH0_ISSUER_BASE_URL='https://YOUR_AUTH0_DOMAIN.auth0.com'
APP_BASE_URL='http://localhost:3000'
# Your Auth0 tenant domain
AUTH0_DOMAIN='YOUR_AUTH0_DOMAIN.auth0.com'
# Your Auth0 application's Client ID
AUTH0_CLIENT_ID='YOUR_AUTH0_CLIENT_ID'
# Your Auth0 application's Client Secret
Expand Down
7 changes: 4 additions & 3 deletions Sample-01/api-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ const jwksRsa = require('jwks-rsa');

const app = express();
const port = process.env.API_PORT || 3001;
const baseUrl = process.env.AUTH0_BASE_URL;
const issuerBaseUrl = process.env.AUTH0_ISSUER_BASE_URL;
const baseUrl = process.env.APP_BASE_URL;
const domain = process.env.AUTH0_DOMAIN;
const issuerBaseUrl = `https://${domain}`;
const audience = process.env.AUTH0_AUDIENCE;

if (!baseUrl || !issuerBaseUrl) {
if (!baseUrl || !domain) {
throw new Error('Please make sure that the file .env.local is in place and populated');
}

Expand Down
3 changes: 0 additions & 3 deletions Sample-01/app/api/auth/[auth0]/route.js

This file was deleted.

19 changes: 13 additions & 6 deletions Sample-01/app/api/shows/route.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0';
import { NextResponse } from 'next/server';
import { auth0 } from '../../../lib/auth0';

export const GET = withApiAuthRequired(async function shows(req) {
export const GET = async function shows() {
try {
const session = await auth0.getSession();

if (!session) {
return NextResponse.json(
{ error: 'Not authenticated' },
{ status: 401 }
);
}

const res = new NextResponse();
const { accessToken } = await getAccessToken(req, res, {
scopes: ['read:shows']
});
const { token: accessToken } = await auth0.getAccessToken();
const apiPort = process.env.API_PORT || 3001;
const response = await fetch(`http://localhost:${apiPort}/api/shows`, {
headers: {
Expand All @@ -19,4 +26,4 @@ export const GET = withApiAuthRequired(async function shows(req) {
} catch (error) {
return NextResponse.json({ error: error.message }, { status: error.status || 500 });
}
});
};
7 changes: 3 additions & 4 deletions Sample-01/app/csr/page.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
'use client';

import React from 'react';
import { withPageAuthRequired } from '@auth0/nextjs-auth0/client';

export default withPageAuthRequired(function CSRPage() {
export default function CSRPage() {
return (
<>
<div className="mb-5" data-testid="csr">
Expand All @@ -20,10 +19,10 @@ export default withPageAuthRequired(function CSRPage() {
custom <a href="https://nextjs.org/docs/advanced-features/custom-app">App Component</a> with it.
</p>
<p>
You can also fetch the user profile by calling the <code>/api/auth/me</code> API route.
You can also fetch the user profile by calling the <code>/auth/profile</code> API route.
</p>
</div>
</div>
</>
);
});
};
8 changes: 1 addition & 7 deletions Sample-01/app/external/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

import React, { useState } from 'react';
import { Button } from 'reactstrap';
import { withPageAuthRequired } from '@auth0/nextjs-auth0/client';

import Loading from '../../components/Loading';
import ErrorMessage from '../../components/ErrorMessage';
import Highlight from '../../components/Highlight';

function External() {
export default function External() {
const [state, setState] = useState({ isLoading: false, response: undefined, error: undefined });

const callApi = async () => {
Expand Down Expand Up @@ -68,8 +67,3 @@ function External() {
</>
);
}

export default withPageAuthRequired(External, {
onRedirecting: () => <Loading />,
onError: error => <ErrorMessage>{error.message}</ErrorMessage>
});
6 changes: 3 additions & 3 deletions Sample-01/app/layout.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import NavBar from '../components/NavBar';
import { Container } from 'reactstrap';
import Footer from '../components/Footer';
import React from 'react';
import { UserProvider } from '@auth0/nextjs-auth0/client';
import { Auth0Provider } from '@auth0/nextjs-auth0';

export default function RootLayout({ children }) {
return (
Expand All @@ -20,13 +20,13 @@ export default function RootLayout({ children }) {
<link rel="stylesheet" href="https://cdn.auth0.com/js/auth0-samples-theme/1.0/css/auth0-theme.min.css" />
</head>
<body>
<UserProvider>
<Auth0Provider>
<main id="app" className="d-flex flex-column h-100" data-testid="layout">
<NavBar />
<Container className="flex-grow-1 mt-5">{children}</Container>
<Footer />
</main>
</UserProvider>
</Auth0Provider>
</body>
</html>
);
Expand Down
10 changes: 2 additions & 8 deletions Sample-01/app/profile/page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

import React from 'react';
import { Row, Col } from 'reactstrap';
import { useUser, withPageAuthRequired } from '@auth0/nextjs-auth0/client';
import { useUser } from '@auth0/nextjs-auth0';

import Loading from '../../components/Loading';
import ErrorMessage from '../../components/ErrorMessage';
import Highlight from '../../components/Highlight';

function Profile() {
export default function Profile() {
const { user, isLoading } = useUser();

return (
Expand Down Expand Up @@ -41,8 +40,3 @@ function Profile() {
</>
);
}

export default withPageAuthRequired(Profile, {
onRedirecting: () => <Loading />,
onError: error => <ErrorMessage>{error.message}</ErrorMessage>
});
47 changes: 22 additions & 25 deletions Sample-01/app/ssr/page.jsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,28 @@
import React from 'react';
import { getSession, withPageAuthRequired } from '@auth0/nextjs-auth0';
import { auth0 } from '../../lib/auth0';

import Highlight from '../../components/Highlight';

export default withPageAuthRequired(
async function SSRPage() {
const { user } = await getSession();
return (
<>
<div className="mb-5" data-testid="ssr">
<h1 data-testid="ssr-title">Server-side Rendered Page</h1>
<div data-testid="ssr-text">
<p>
You can protect a server-side rendered page by wrapping it with <code>withPageAuthRequired</code>. Only
logged in users will be able to access it. If the user is logged out, they will be redirected to the login
page instead.{' '}
</p>
</div>
export default async function SSRPage() {
const { user } = await auth0.getSession();
return (
<>
<div className="mb-5" data-testid="ssr">
<h1 data-testid="ssr-title">Server-side Rendered Page</h1>
<div data-testid="ssr-text">
<p>
You can protect a server-side rendered page by wrapping it with <code>withPageAuthRequired</code>. Only
logged in users will be able to access it. If the user is logged out, they will be redirected to the login
page instead.{' '}
</p>
</div>
<div className="result-block-container" data-testid="ssr-json">
<div className="result-block">
<h6 className="muted">User</h6>
<Highlight>{JSON.stringify(user, null, 2)}</Highlight>
</div>
</div>
<div className="result-block-container" data-testid="ssr-json">
<div className="result-block">
<h6 className="muted">User</h6>
<Highlight>{JSON.stringify(user, null, 2)}</Highlight>
</div>
</>
);
},
{ returnTo: '/ssr' }
);
</div>
</>
);
};
10 changes: 5 additions & 5 deletions Sample-01/components/NavBar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
DropdownMenu,
DropdownItem
} from 'reactstrap';
import { useUser } from '@auth0/nextjs-auth0/client';
import { useUser } from '@auth0/nextjs-auth0';

import PageLink from './PageLink';
import AnchorLink from './AnchorLink';
Expand Down Expand Up @@ -61,7 +61,7 @@ const NavBar = () => {
{!isLoading && !user && (
<NavItem id="qsLoginBtn">
<AnchorLink
href="/api/auth/login"
href="/auth/login"
className="btn btn-primary btn-margin"
tabIndex={0}
testId="navbar-login-desktop">
Expand Down Expand Up @@ -92,7 +92,7 @@ const NavBar = () => {
</PageLink>
</DropdownItem>
<DropdownItem id="qsLogoutBtn">
<AnchorLink href="/api/auth/logout" icon="power-off" testId="navbar-logout-desktop">
<AnchorLink href="/auth/logout" icon="power-off" testId="navbar-logout-desktop">
Log out
</AnchorLink>
</DropdownItem>
Expand All @@ -103,7 +103,7 @@ const NavBar = () => {
{!isLoading && !user && (
<Nav className="d-md-none" navbar>
<AnchorLink
href="/api/auth/login"
href="/auth/login"
className="btn btn-primary btn-block"
tabIndex={0}
testId="navbar-login-mobile">
Expand Down Expand Up @@ -140,7 +140,7 @@ const NavBar = () => {
</NavItem>
<NavItem id="qsLogoutBtn">
<AnchorLink
href="/api/auth/logout"
href="/auth/logout"
className="btn btn-link p-0"
icon="power-off"
testId="navbar-logout-mobile">
Expand Down
18 changes: 18 additions & 0 deletions Sample-01/lib/auth0.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Auth0Client } from "@auth0/nextjs-auth0/server";

// Initialize the Auth0 client
export const auth0 = new Auth0Client({
// Options are loaded from environment variables by default
// Ensure necessary environment variables are properly set
// domain: process.env.AUTH0_DOMAIN,
// clientId: process.env.AUTH0_CLIENT_ID,
// clientSecret: process.env.AUTH0_CLIENT_SECRET,
// appBaseUrl: process.env.APP_BASE_URL,
// secret: process.env.AUTH0_SECRET,
authorizationParameters: {
// In v4, the AUTH0_SCOPE and AUTH0_AUDIENCE environment variables are no longer automatically picked up by the SDK.
// Instead, we need to provide the values explicitly.
scope: process.env.AUTH0_SCOPE,
audience: process.env.AUTH0_AUDIENCE,
}
});
39 changes: 39 additions & 0 deletions Sample-01/middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { NextResponse } from "next/server";
import { auth0 } from "./lib/auth0"

export async function middleware(request) {
const authRes = await auth0.middleware(request);

// authentication routes — let the middleware handle it
if (request.nextUrl.pathname.startsWith("/auth")) {
return authRes;
}

// public routes — no need to check for session
if (request.nextUrl.pathname === ("/")) {
return authRes;
}

const { origin } = new URL(request.url)
const session = await auth0.getSession()

// user does not have a session — redirect to login
if (!session) {
return NextResponse.redirect(`${origin}/auth/login`)
}

return authRes
}

export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
* - api (API routes)
*/
"/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt|api).*)",
],
}
Loading