-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
CredentialsProvider session token cookie not updated on getServerSideProps #4075
Comments
Please try |
Thank You @ThangHuuVu . Just tried like this; const session = await getServerSession(ctx, {
providers: [],
}); Receiving below error just when I call getServerSession ; [next-auth][error][JWT_SESSION_ERROR]
https://next-auth.js.org/errors#jwt_session_error Invalid Compact JWE {
message: 'Invalid Compact JWE',
stack: 'JWEInvalid: Invalid Compact JWE\n' +
' at compactDecrypt (D:\\Dev\\GIT\\nextauth-credential-rotate\\node_modules\\jose\\dist\\node\\cjs\\jwe\\compact\\decrypt.js:16:15)\n' +
' at jwtDecrypt (D:\\Dev\\GIT\\nextauth-credential-rotate\\node_modules\\jose\\dist\\node\\cjs\\jwt\\decrypt.js:8:61)\n' +
' at Object.decode (D:\\Dev\\GIT\\nextauth-credential-rotate\\node_modules\\next-auth\\jwt\\index.js:64:34)\n' +
' at processTicksAndRejections (internal/process/task_queues.js:95:5)\n' +
' at async Object.session (D:\\Dev\\GIT\\nextauth-credential-rotate\\node_modules\\next-auth\\core\\routes\\session.js:41:28)\n' +
' at async NextAuthHandler (D:\\Dev\\GIT\\nextauth-credential-rotate\\node_modules\\next-auth\\core\\index.js:96:27)\n' +
' at async getServerSession (D:\\Dev\\GIT\\nextauth-credential-rotate\\node_modules\\next-auth\\next\\index.js:67:19)\n' +
' at async getServerSideProps (webpack-internal:///./pages/index.tsx:51:21)\n' +
' at async Object.renderToHTML (D:\\Dev\\GIT\\nextauth-credential-rotate\\node_modules\\next\\dist\\server\\render.js:589:20)\n' +
' at async doRender (D:\\Dev\\GIT\\nextauth-credential-rotate\\node_modules\\next\\dist\\server\\base-server.js:879:38)',
name: 'JWEInvalid'
} Should I call it differently ? |
To use export const authOptions: NextAuthOptions = {
secret: process.env.TOKEN_SECRET,
// other configs...
}
export default NextAuth(authOptions); In const session = await getServerSession(ctx, authOptions); |
@ThangHuuVu @balazsorban44 getServerSession works the way I need, thank you a lot 👍 One point I observed is, I need to supply default token properties explicitly; const defaultToken = {
name: '',
email: '',
picture: '',
};
function createToken(username: string) {
return {
...defaultToken,
username,
accessTokenExpires:
Date.now() + parseInt(process.env.TOKEN_REFRESH_PERIOD) * 1000,
};
} If I try to create the token without them; function createToken(username: string) {
return {
username,
accessTokenExpires:
Date.now() + parseInt(process.env.TOKEN_REFRESH_PERIOD) * 1000,
};
} I received error - Error: Error serializing `.session.user.name` returned from `getServerSideProps` in "/".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value. Maybe those default props can be supplied internally. So, we wouldn't have to supply them. Thanks again & regards |
@ThangHuuVu using getToken right after I called
|
@ThangHuuVu @balazsorban44 a very elegant solution would be to return the token together with the session like this; const {session, token} = await getServerSession(ctx, authOptions); What would you think? |
The session is usually a subset of the token, the part that you want to expose to the client. If you want the token, you can use |
@balazsorban44 not all the next.js apps run on the internet. Some are in house developed enterprise applications. And the users are in Active Directory, no social providers :( So, we have to use LDAP to make the authentication. Credentials Provider seems the first option. Is your recommened way to use a custom oauth provider for this situation? Can you suggest any LDAP oauth implementation? Thanks |
Prohibiting Credentials Provider from using database isn't it too imperative? Why don't you just make your recommendation about its use and let the user decide? I'm sure, in most of the cases a simple JWT based authentication workflow is perfectly enough. Trying to implement a custom OAuth provider just to be able to use a database, is an overkill ! |
You don't have to create a custom OAuth Identity Provider to use it with the Credentials Provider. In that case, you should just use it directly, as we support OAuth out of the box. There are way too many footguns when one tries to implement custom auth, so we discourage anyone doing so. This is stated in our docs: https://next-auth.js.org/providers/credentials It would complicate our codebase unnecessarily. We do support Azure AD and Azure AD B2C by the way, you can check if that's an option for your use case. Looks like this is turning into a feature request, so I'll close. We are not going to support databases with the credentials provider in the foreseeable future. We are recommending best practices, and it might be that your use case is just outside the scope of NextAuth.js or what we would like to help with. You can utilize NextAuth.js for your use case through the CredentialsProvider and the |
It's save my day! Thks so much! may it would be very welcome to official docs of next-auth! |
Tried to make it work but unable to do that in any way Using Keycloak as my provider the following code is being used const session = await getServerSession(context.req, context.res, authOptions); And my authOptions function getProviderKeyCloak() {
return KeycloakProvider({
clientId: process.env.KEYCLOAK_CID!,
clientSecret: process.env.KEYCLOAK_SID!,
issuer: process.env.KEYCLOAK_ISS!,
name: "Athena Auth",
style: {
logo: "",
logoDark: "",
bg: "#fff",
text: "#000",
bgDark: "#fff",
textDark: "#000",
}
})
}
export const authOptions: AuthOptions = {
secret: process.env.NEXTAUTH_SECRET,
pages: {
signIn: "/auth/signin",
newUser: "/profile",
signOut: "/"
},
providers: [ getProviderKeyCloak() ]
} I am trying to debug it myself but still unable to figure out what is really happening to make this Invalid JWE Compact stops Tried everything in the post but still not being able to work it out |
I am getting this error in Next 13.4.19 and I cant figure out why. I do not have this error in my next 13.1.6 app. |
Environment
System:
OS: Windows 10 10.0.19042
CPU: (8) x64 Intel(R) Xeon(R) CPU E3-1505M v6 @ 3.00GHz
Memory: 5.44 GB / 15.86 GB
Binaries:
Node: 14.17.2 - C:\Program Files\nodejs\node.EXE
Yarn: 1.22.4 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 6.14.13 - C:\Program Files\nodejs\npm.CMD
Browsers:
Edge: Spartan (44.19041.1266.0)
Internet Explorer: 11.0.19041.1202
npmPackages:
next: ~12.1.0 => 12.1.0
next-auth: ~4.2.1 => 4.2.1
react: 17.0.2 => 17.0.2
Reproduction URL
https://github.com/killjoy2013/nextauth-credential-rotate
Describe the issue
Hi,
Using CredentialsProvider and need to rotate the token. My [...nextauth.ts] is below;
TOKEN_MAX_AGE
is 3600 seconds andTOKEN_REFRESH_PERIOD
is 60 seconds. So, in 60 seconds after JWT is created, token is supposed to get rotated. Initial token creation is increateToken
and tried to simulate token refresh inrefreshToken
. I putusername
&willExpire
as claims. In Jwt callback, a token is created and returned. Then, encode runs and encoded token returned. Both home page (index.tsx) and cities.tsx hasin their
getServerSideProps
. So, each navigation to home & cities page triggers jwt callback and even though encode function encodes and return a new token,next-auth.session-token
cookie never gets updated. It's just created when user first login, and stays always the same. Normally, I'll decide token rotation in jwt as in token rotation sample in tutorials like this;Since the session token cookie is not updated, this rotation logic fails because the token received in jwt callback is always the same.
How to reproduce
npm i & npm run dev
navigate to
http://localhost:3000/
you'll be redirected to login page. Provide a dummy username and a password
You'll be redirected to home page. Now you can display
next-auth.session-token
cookie now.click
Cities
in the left menu and you'll navigate to cities page.click toolbar to go back home page.
In every navigation between pages,
getServerSideProps
runs withgetSession
andgetToken
inside.Note that,
next-auth.session-token
is not changing :-(Close the browser and wait until token refresh period ( 60 seconds ) has passed. Then open a browser and navigate to
http://localhost:3000/cities
Now, notice that,
next-auth.session-token
cookie still has the old token from last login before closing the browser.Expected behavior
next-auth.session-token
is supposed to get updated with the returned token from encode.On the client side, we can force the token to update using
However, users can directly navigate to
http://localhost:3000/cities
In this case, ongetServerSideProps
an updated token is supposed to be obtained because this token will be used in a graphql query that will be run from serverside.The text was updated successfully, but these errors were encountered: