Skip to content

Instantly share code, notes, and snippets.

@100milliongold
Last active January 16, 2023 02:06
Show Gist options
  • Select an option

  • Save 100milliongold/0aaa0871899fddac5769a5169a8629cd to your computer and use it in GitHub Desktop.

Select an option

Save 100milliongold/0aaa0871899fddac5769a5169a8629cd to your computer and use it in GitHub Desktop.
nextauth + keycloak + typescript
AUTH_CLIENT_ID=
AUTH_CLIENT_SECRET=
AUTH_ISSUER=
NEXTAUTH_URL=
import NextAuth from "next-auth";
import KeycloakProvider from "next-auth/providers/keycloak";
export default NextAuth({
// Configure one or more authentication providers
providers: [
KeycloakProvider({
clientId: process.env.AUTH_CLIENT_ID!,
clientSecret: process.env.AUTH_CLIENT_SECRET!,
issuer: process.env.AUTH_ISSUER,
}),
],
callbacks: {
async session({ session, token, user }) {
session.user.id = token.id as string;
session.accessToken = token.accessToken as string;
return session;
},
async jwt({ token, user, account, profile, isNewUser }) {
if (user) {
token.id = user.id;
}
if (account) {
token.accessToken = account.access_token;
}
return token;
},
},
});
import type { NextPage } from "next";
import { signIn, signOut, useSession } from "next-auth/react";
import Head from "next/head";
import styles from "../styles/Home.module.css";
import axios from "axios";
const Home: NextPage = () => {
const { data: session, status } = useSession();
const loading = status === "loading";
const logout = async (): Promise<void> => {
const {
data: { path },
} = await axios.get("/api/auth/logout");
await signOut({ redirect: false });
window.location.href = path;
};
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
</Head>
<main className={styles.main}>
{!session && (
<>
<span className={styles.notSignedInText}>
You are not signed in
</span>
<a
href={`/api/auth/signin`}
className={styles.buttonPrimary}
onClick={(e) => {
e.preventDefault();
signIn("keycloak");
}}
>
Sign in
</a>
</>
)}
{session?.user && (
<>
{session.user.image && (
<span
style={{ backgroundImage: `url('${session.user.image}')` }}
className={styles.avatar}
/>
)}
<span className={styles.signedInText}>
<small>Signed in as</small>
<br />
<strong>{session.user.email ?? session.user.name}</strong>
</span>
<a
href={`/api/auth/signout`}
className={styles.button}
onClick={(e) => {
e.preventDefault();
logout();
}}
>
Sign out
</a>
</>
)}
</main>
</div>
);
};
export default Home;
import { getSession } from "next-auth/react";
import type { NextApiRequest, NextApiResponse } from "next";
const logout = (req: NextApiRequest, res: NextApiResponse) => {
const path = `${
process.env.AUTH_ISSUER
}/protocol/openid-connect/logout?redirect_uri=${encodeURIComponent(
process.env.NEXTAUTH_URL || ""
)}`;
res.status(200).json({ path });
};
export default logout;
import NextAuth, { Session as originSession } from "next-auth";
declare global {
namespace NodeJS {
interface ProcessEnv {
AUTH_CLIENT_ID: string;
AUTH_CLIENT_SECRET: string;
AUTH_ISSUER: string;
NEXTAUTH_URL: string;
}
}
}
declare module "next-auth" {
/**
* Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
*/
interface Session extends originSession {
accessToken?: string | null;
user: {
id?: string | null;
};
}
}
@100milliongold
Copy link
Author

키클락과 next.js 연동에 필요

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment