I configure nextauth with Keycloak provider I redirected to this page api/auth/error if I left tab open for a while. #10837
Unanswered
ArslanAkhtar
asked this question in
Help
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi, I am new with nextauth. I have configure keylcloak with nextauth it is working fine except when I left site open for a while in other tab it redirected to api/auth/error page and does not show any specific errors It just give redirect option to redirect on site. I have written auto redirect script on the following url api/auth/error I have created error.tsx
`import { NextApiResponse, NextApiRequest } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.writeHead(307, { Location: '/' });
res.end();
}
`
Then found this is not the write way because it didnt give any error if the keycloak went down.
This is my authOptions file
`import { getServerSession, type NextAuthOptions } from 'next-auth';
import KeycloakProvider from 'next-auth/providers/keycloak';
import { env } from '@env';
import { TokenSet } from 'next-auth/core/types';
import { JWT } from 'next-auth/jwt';
import axios from 'axios';
async function refreshAccessToken(token: JWT) {
try {
const response = await fetch(
${env.KEYCLOAK_ISSUER}/protocol/openid-connect/token
, {headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
client_id: env.KEYCLOAK_CLIENT_ID,
client_secret: env.KEYCLOAK_CLIENT_SECRET,
grant_type: 'refresh_token',
refresh_token: token.refresh_token ?? ''
}),
method: 'POST'
});
}
export const authOptions: NextAuthOptions = {
session: {
strategy: 'jwt'
},
secret: env.NEXTAUTH_SECRET,
callbacks: {
function
};
export async function getServerAuthSession(req: any, res: any) {
return await getServerSession(req, res, authOptions);
}
declare module 'next-auth/core/types' {
interface Session {
access_token?: string;
refresh_token?: string;
expires_at?: number;
user: DefaultSession['user'] & { id?: string; roles?: string[]; username?: string; email?: string };
error?: 'RefreshAccessTokenError';
}
}
declare module 'next-auth' {
interface Profile {
roles?: string[];
preferred_username?: string;
}
}
declare module 'next-auth/jwt' {
interface JWT {
id_token?: string;
preferred_username?: string;
username?: string;
access_token?: string;
refresh_token?: string;
roles?: string[];
expires_at?: number;
sub?: string;
error?: 'RefreshAccessTokenError';
}
}`
Beta Was this translation helpful? Give feedback.
All reactions