auth cookie
How can I authenticate my nuxt3 app against spring boot 3 app, java app uses JSESSIONID cookie to track sessions. I need to authenticate and then somehow include this cookie to all subsequent requests + protect pages with midleware.
nuxt-auth module for Nuxt3).nuxt-auth official package will probably do some incredible black magic and cool DX.
nuxt-authnuxt-auth// middleware/auth.global.ts
const userAuthenticated = (accessToken: string | null | undefined) => {
return accessToken !== undefined && accessToken !== null;
};
/**
* Auth middleware
*/
export default defineNuxtRouteMiddleware((to) => {
// Skip this middleware on the client, as we are using an httpOnly cookie for authentication
if (process.client) return;
// Get the access token from the cookie
const accessToken = useCookie('accessToken');
// If the user tries to access any route (except /login) and is not authenticated
if (
to.path !== '/login' &&
!userAuthenticated(accessToken.value)
) {
// Redirect to /login
return navigateTo('/login');
}
// If the user tries to access /login and is authenticated
if (
to.path === '/login' &&
userAuthenticated(accessToken.value)
) {
// Redirect to /
return navigateTo('/');
}
// If the user is authenticated, allow the request to continue
return;
});// /server/api/auth/login.ts
import { CryptoUtil } from 'crypto-util';
import { UserSchema } from '~/server/model/user.schema';
/**
* Test route
*/
export default defineEventHandler(async (event) => {
// Get the request body
const body = await readBody(event);
// Try to find the user with the given credentials
const user = await UserSchema.findOne({
email: body.email,
password: body.password,
});
// If the user is not found, throw an error
if (!user) {
throw createError({
statusCode: 404,
statusMessage: 'User not found',
});
}
// Generate a new access token
const accessToken = CryptoUtil.generateRandomString(256);
// Set the access token in the user
user.accessToken = accessToken;
await user.save();
// Set the access token in a httpOnly cookie for the client
setCookie(event, 'accessToken', accessToken, {
secure: true,
httpOnly: true,
sameSite: 'strict',
// Expires in 1 year
expires: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7 * 365),
});
// Redirect the user to the dashboard
return sendRedirect(event, '/');
});