H
Hono2mo ago
iEmix

How to add custom message to error Bearer Auth

export const auth = bearerAuth({
verifyToken: async (accessToken: string, c: AppContext) => {
try {
const jwtPayload: JWTPayload = await verifyAccessToken(accessToken);
const user: AuthUser = jwtPayload.user as AuthUser;
c.set('user', user);
} catch (err) {
return false;
}

return true;
},
});
export const auth = bearerAuth({
verifyToken: async (accessToken: string, c: AppContext) => {
try {
const jwtPayload: JWTPayload = await verifyAccessToken(accessToken);
const user: AuthUser = jwtPayload.user as AuthUser;
c.set('user', user);
} catch (err) {
return false;
}

return true;
},
});
I want add custom message when failed for example, JWT Access token expired
1 Reply
iEmix
iEmix2mo ago
My solution is working now, but I'm not sure if it's the best approach
export const jwt = bearerAuth({
verifyToken: async (accessToken: string, c: AppContext): Promise<boolean> => {
try {
const jwtPayload: JWTPayload = await verifyAccessToken(accessToken);
c.set('user', jwtPayload.user as AuthUser);
return true;
} catch (err) {
throw new Error(err instanceof JwtTokenExpired ? 'Expired JWT Token' : 'Authentication failed');
}
},
});

export const auth: MiddlewareHandler = async (c: AppContext, next: Next): Promise<any> => {
try {
await jwt(c, next);
} catch (e: any) {
return c.json({error: e.message && e.message.length > 0 ? e.message : 'Authentication failed'}, 401);
}
};
export const jwt = bearerAuth({
verifyToken: async (accessToken: string, c: AppContext): Promise<boolean> => {
try {
const jwtPayload: JWTPayload = await verifyAccessToken(accessToken);
c.set('user', jwtPayload.user as AuthUser);
return true;
} catch (err) {
throw new Error(err instanceof JwtTokenExpired ? 'Expired JWT Token' : 'Authentication failed');
}
},
});

export const auth: MiddlewareHandler = async (c: AppContext, next: Next): Promise<any> => {
try {
await jwt(c, next);
} catch (e: any) {
return c.json({error: e.message && e.message.length > 0 ? e.message : 'Authentication failed'}, 401);
}
};
Want results from more Discord servers?
Add your server