Replies: 1 comment 3 replies
-
You can get authjs.session-token from the cookies on the Next.js (server action), decode and pass it to the backend in the headers. There you check it with guards for validity. // Next.js
// /src/actions/sessionAPI.tsx
import {decode} from '@auth/core/jwt'
import {cookies} from 'next/headers'
const BASE = process.env.API_BASE
const isProduction = process.env.NODE_ENV === 'production';
const COOKIES_NAME = isProduction ? '__Secure-next-auth.session-token' : 'authjs.session-token'
interface SessionParams {
type?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
url: string
init?: RequestInit
}
async function decodeCookies() {
try {
const cookieToken = cookies()?.get(COOKIES_NAME)?.value
if (!cookieToken) return null
return await decode({
secret: process.env.AUTH_SECRET as string,
salt: COOKIES_NAME,
token: cookieToken,
})
} catch (err) {
console.log(' === sessionAPI | decodeCookies:>> ', err)
return null
}
}
export default async function sessionAPI(params: SessionParams) {
try {
const { type = 'GET', url, init } = params
const tokens = await decodeCookies()
if (!tokens?.accessToken || Date.now() > tokens?.accessTokenExp * 1000) {
console.log(' === sessionAPI | status === 401 (Unautorized)')
return null
}
const headers = {
Authorization: `Bearer ${tokens?.accessToken}`,
...init?.headers,
}
const res = await fetch(BASE + url, { method: type, ...init, headers })
return await res.json()
} catch (err) {
console.log(' === sessionAPI:>> ', err)
return null
}
} |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Frontend authentication works successfully already
Frontend code
Now I want to use the token we get from Microsoft Entra in the backend
So I take the token from the cookie (
__Secure-authjs.pkce.code_verifier=ey...<Token with 5 parts>
and put it in the
Authorization: Bearer ey...<Token with 5 parts>
headerThe I use this code in my NestJS auth guard to decrypt the token:
I double checked the AUTH_TOKEN config var is exactly what is configured in the frontend App Service on Azure
I am not 100% sure whether
authjs.session-token
is the valid salt. A colleague told be I should set it like thatAlso have seen a lot of examples out there using an empty string as salt. Tried that - same result. Key is not valid
This is the error I get
Update: I also tried with the salt
__Secure-authjs.session-token
but I still get the same errorBeta Was this translation helpful? Give feedback.
All reactions