Skip to content

Commit

Permalink
fix(auth): Replace jsonwebtoken with jose for JWT decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
phoenixpereira committed Feb 5, 2025
1 parent 9c18244 commit 3a3549b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 106 deletions.
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"@t3-oss/env-nextjs": "^0.11.1",
"drizzle-orm": "^0.38.3",
"drizzle-zod": "^0.6.1",
"jsonwebtoken": "^9.0.2",
"jose": "^5.9.6",
"just-submit": "^0.0.8",
"ky": "^1.7.4",
"luxon": "^3.5.0",
Expand All @@ -48,7 +48,6 @@
"devDependencies": {
"@next/env": "^15.1.3",
"@trivago/prettier-plugin-sort-imports": "^5.2.0",
"@types/jsonwebtoken": "^9.0.8",
"@types/luxon": "^3.4.2",
"@types/md5": "^2.3.5",
"@types/node": "^22.10.3",
Expand Down
98 changes: 3 additions & 95 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

24 changes: 15 additions & 9 deletions src/auth.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import jwt from 'jsonwebtoken';
import { decodeJwt } from 'jose';
import NextAuth from 'next-auth';
import type { Session } from 'next-auth';
import Keycloak from 'next-auth/providers/keycloak';

interface KeycloakToken {
realm_access?: {
roles?: string[];
};
sub?: string;
given_name?: string;
family_name?: string;
email?: string;
name?: string;
}

interface ExtendedSession extends Session {
user: {
id?: string;
Expand All @@ -19,20 +30,16 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
trustHost: true,
callbacks: {
async jwt({ token, user, account, profile }) {
// Add user information to the JWT token
if (account?.access_token) {
const decodedToken = jwt.decode(account?.access_token);
if (decodedToken && typeof decodedToken !== 'string') {
if (decodedToken?.realm_access?.roles.includes('restricted-access')) {
token.isCommittee = true;
}
const decodedToken = decodeJwt<KeycloakToken>(account.access_token);
if (decodedToken?.realm_access?.roles?.includes('restricted-access')) {
token.isCommittee = true;
}
}
if (user) {
token.email = user.email;
token.name = user.name;
}

if (profile) {
token.id = profile.sub;
token.firstName = profile.given_name;
Expand All @@ -41,7 +48,6 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
return token;
},
async session({ session, token }) {
// Add user ID and names to the session
if (token) {
session.user.id = token.id as string;
session.user.email = token.email as string;
Expand Down

0 comments on commit 3a3549b

Please sign in to comment.