admin管理员组

文章数量:1405576

I'm having some trouble getting my cookie back when I try to login with the Local provider in NuxtAuth.

Here's my nuxt.config.ts

RuntimeConfig: {
    baseURL: '/api/auth'
  },
  auth: {
    isEnabled: true,
    disableServerSideAuth: false,
    originEnvKey: 'NUXT_BASE_URL',
    baseURL: 'http://localhost:3000/api/auth',
    provider: {
      type: 'local',
      endpoints: {
        signIn: { path: '/login', method: 'post' },
        signOut: { path: '/logout', method: 'post' },
        signUp: { path: '/register', method: 'post' },
        getSession: { path: '/session', method: 'get' },
      },
      token: {
        signInResponseTokenPointer: '/token',
        type: 'Bearer',
        cookieName: 'auth.token',
        headerName: 'Authorization',
        maxAgeInSeconds: 60 * 60 * 24 * 7, // 7 days,
        sameSiteAttribute: 'none',
        cookieDomain: 'localhost:3000',
        secureCookieAttribute: false,
        httpOnlyCookieAttribute: false,
      }
    },
    sessionRefresh: {
      enablePeriodically: false,
      enableOnWindowFocus: false,
    }
  }

and in my login.post.ts file I have this

   export default defineEventHandler(async (event) => {
      const body = await readBody(event);
      const { email, password } = body;
    
      console.log("Trying to log in:", email);
    
      const [user] = await db
      .select()
      .from(users)
      .where(eq(users.email, email.trim())); // add .trim() just in case
    
    
      console.log("USER", user)
      if (!user) {
        throw createError({
          statusCode: 401,
          statusMessage: 'Invalid credentials (email not found)'
        });
      }
    
      const passwordIsValid = await compare(password, user.passwordHash);
    
      if (!passwordIsValid) {
        throw createError({
          statusCode: 401,
          statusMessage: 'Invalid credentials (wrong password)'
        });
      }
    
      const token = signJwt({
        id: user.id,
        email: user.email,
        name: user.username,
      });
    
      console.log("TOKEN", token)
    
      return { token };
    });

session.get.ts file:

import { verifyJwt } from '~/server/utils/jwt';
import { getHeader } from 'h3';

export default defineEventHandler(async (event) => {
  const authHeader = getHeader(event, 'authorization');

  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return null;
  }

  const token = authHeader.split(' ')[1];
  const user = verifyJwt(token);

  if (!user) return null;

  return { user }; 
});

jwt.ts

import jwt, { SignOptions } from 'jsonwebtoken';

const secret = process.env.AUTH_SECRET || 'super-secret';

export function signJwt(payload: object, expiresIn: string | number = '7d') {
  const options: SignOptions = { expiresIn }; 
  return jwt.sign(payload, secret, options);
}

export function verifyJwt(token: string) {
  try {
    return jwt.verify(token, secret);
  } catch {
    return null;
  }
}

I am a little stuck as I seem to be authenticated when I log in in general, but there is no cookie and I need a cookie for persistent authentication. Any help would be appreciated

本文标签: vuejsCan39t retrieve Cookie with Local Provider in NuxtAuthStack Overflow