Last active
September 27, 2022 18:05
-
-
Save RafalFilipek/a43f8928c471ca523dd39d7a632a884d to your computer and use it in GitHub Desktop.
Hasura + next-auth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import NextAuth, { type NextAuthOptions } from "next-auth"; | |
import { JWT } from "next-auth/jwt"; | |
import * as jwt from "jose"; | |
export const authOptions: NextAuthOptions = { | |
// the rest is just like in tutorials. Session, callbacks etc. | |
jwt: { | |
encode: async ({ secret, token }) => { | |
if (!token) { | |
console.warn("encode: No token provided"); | |
} | |
return await new jwt.SignJWT(token!) | |
.setProtectedHeader({ alg: "HS256" }) | |
.sign(new TextEncoder().encode(secret as string)); | |
}, | |
decode: async ({ secret, token }) => { | |
if (!token) { | |
console.warn("decode: No token provided"); | |
} | |
const { payload } = await jwt.jwtVerify( | |
token!, | |
new TextEncoder().encode(secret as string), | |
{ algorithms: ["HS256"] } | |
); | |
return payload as JWT; | |
}, | |
}, | |
// the rest is just like in tutorials. Session, callbacks etc. | |
}; | |
export default NextAuth(authOptions); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export async function getServerSideProps(context: GetServerSidePropsContext) { | |
// decoded token | |
const token = await getToken({ | |
req: context.req, | |
decode: authOptions.jwt?.decode, | |
}); | |
// raw token | |
const raw = await getToken({ req: context.req, raw: true }); | |
return { | |
props: { | |
token, | |
raw, | |
session: await unstable_getServerSession( | |
context.req, | |
context.res, | |
authOptions | |
), | |
}, | |
}; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import withAuth from "next-auth/middleware"; | |
import * as jwt from "jose"; | |
import { JWTDecodeParams } from "next-auth/jwt"; | |
async function decode({ secret, token }: JWTDecodeParams) { | |
if (!token) { | |
console.log("middleware-decode: No token provided"); | |
} | |
const { payload } = await jwt.jwtVerify( | |
token!, | |
new TextEncoder().encode(secret as string), | |
{ | |
algorithms: ["HS256"], | |
} | |
); | |
return payload; | |
} | |
export default withAuth({ | |
jwt: { decode }, | |
callbacks: { | |
authorized: ({ token }) => !!token, | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment