atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
973 stars 91 forks source link

Use in multiple domains... #279

Open angelorc opened 1 week ago

angelorc commented 1 week ago

I have a scenario were the backend is on localhost:3001 and the frontend is on localhost:3000

I'm tring to login from localhost:3000 but I was not luky to get the session. How can I use nuxt-auth-utils when the backend is on a different domain?

atinux commented 1 week ago

If your backend provides you a JTW, you cam simply use useCookie from Nuxt to store the session and useState() to keep your user.

angelorc commented 1 week ago

I actually created a cors middleware

import type { H3CorsOptions } from 'h3'

export default defineEventHandler(async (event) => {
  const _headerOrigin = getRequestHeader(event, 'origin')

  let origin: H3CorsOptions['origin']
  if (_headerOrigin) {
    origin = [_headerOrigin]
  }

  handleCors(event, { 
    origin,
    credentials: true 
  })
})

but I'm not sure how secure is this.

This is the scenario:

the frontend and the backend are open source, the goal is to use the frontend to connect to other backend (for example blusky) image

atinux commented 1 week ago

One solution is to to create an API route in your frontend that call your backend so you can avoid using CORS.

I don't see many issues for CORS as long as you whitelist the hosts.

angelorc commented 1 week ago

I don't want to use an api route or a proxy because this is also a trpc router that an user could use. I think one of the best way is to create a cors middleware and allow only trusted origins, something like this

import type { H3CorsOptions } from 'h3'

const ALLOWED_ORIGINS = [
  'https://domain0...',
  'https://domain1...',
]

export default defineEventHandler(async (event) => {
  const _headerOrigin = getRequestHeader(event, 'origin')

  let origin: H3CorsOptions['origin']
  if (_headerOrigin && ALLOWED_ORIGINS.includes(_headerOrigin)) {
    origin = [_headerOrigin]
  } else {
    origin = ['https://defaultdomain']
  }

  handleCors(event, { 
    origin,
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE'],
    allowedHeaders: ['Content-Type', 'Authorization'],
    maxAge: 3600
  })
})