How to securely setup an OAuth2 flow on a backend domain that is separate from the frontend domain?

Viewed 18

I am hosting a Nest.js express server that uses passport.js to authenticate a user. The current flow is as follows: https://backend.com/api/login -> OAuth2 Login Process -> Redirect to https://backend.com/

A cookie is set in the browser that contains a session id that is stored in the backend database.

The config with express-session and prisma-session-store

app.use(
        session({
            cookie: {
                maxAge: 7 * 24 * 60 * 60 * 1000 // ms
            },
            secret: process.env.SESSION_SECRET ?? '',
            resave: true,
            saveUninitialized: true,
            store: new PrismaSessionStore(prismaService, {
                checkPeriod: 2 * 60 * 1000, //ms
                dbRecordIdIsSessionId: true,
                dbRecordIdFunction: undefined
            })
        })
    );

Now all of this works fine when the user is navigating using the backend routes in the browser. However, I intended on hosting a frontend on a separate domain, where a user can login, go through the backend OAuth2 process, and somehow be authorized to do things on the frontend.

So the new flow would be something like this:

https://frontend.com/ (User clicks login button that calls GET backend.com/login) -> OAuth2 Login -> Redirect to https://frontend.com/home with some credentials

But as far as I learned, setting a cookie from a different domain is a big no no due to security. However I have seen some hacky solutions but I would like to stay away from bad practices.

So my question is, in order to accomplish what I want, do I have to host the backend & frontend on the same domain, possibly different sub domains? Is there really no way to fully separate the front/backend if I want a user to go through an OAuth2 flow?

I'm stumped on this. Most solutions I've seen mention just putting both applications on the same domain.

I came across this helpful article on this subject: https://www.scottbrady91.com/oauth/cheat-sheet-oauth-for-browser-based-applications

I think I was going for an Implicit Auth flow, but the API and OAuth stuff is being done on the same server.

For the record, when I setup a button on the frontend to call the backend/login endpoint, I get this CORS error which is another problem. Even though I allowed my domain, the OAuth2 redirect is not happy with it.

Access to XMLHttpRequest at 'https://www.twitch.tv/login?client_id=xxx'
 (redirected from 'https://backend.com/api/auth/twitch/login') from 
origin 'https://frontend.com' has been blocked by CORS policy: No 
'Access-Control-Allow-Origin' header is present on the requested 
resource.

I don't really see a simple solution to this as I don't have control over the server that authenticates a user.

0 Answers
Related