Oauth2 method for callback URL from backend to frontend
Asked Answered
O

1

6

I have a frontend javascript (svelte) and a go backend API. The front end calls the go backend URL to generate an OAuth2 token from github. The backend replies with the crafted url as its response)

https://github.com/login/oauth/authorize?access_type=online&client_id=xxxxxxx&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fapi%2Fv1%2Fcallback&response_type=code&scope=user%3Aemail&state=state

This url is opened by the user with location.assign(authUrl);

The actual full code:

const authUrl = await fetch('http://localhost:8080/api/v1/authurl', {
  method: 'GET',
  headers: {
                'Content-Type': 'application/json'
            }
        }).then(res => res.json()).then(data => data.url);

// Redirect the user to the GitHub authorization URL
location.assign(authUrl);

The backend then handles the callback, which then performs the exchange and receives a valid OAuth2 token (yay!)

From here I need to inform the client the transaction has completed, but I am unsure of how to do this (this is where I freely admit I suck at frontend and don't have much experience). I have decided to return a httponly session cookie to the frontend and store the GitHub OAuth2 token securely on the backend, but how should I get this token to the frontend so that it can store it?

Keep in mind there is not fetch from the client, the backend API initiates with the call back.

One thing I can do is redirect;

cookie := &http.Cookie{
            Name:     "token",
            Value:    jwt_token,
            MaxAge:   3600,
            Path:     "/",
            Domain:   "localhost",
            Secure:   false,
            HttpOnly: true,
}
c.SetCookie(cookie.Name, cookie.Value, cookie.MaxAge, cookie.Path, cookie.Domain, cookie.Secure, cookie.HttpOnly)

c.Redirect(http.StatusFound, "http://localhost:3000/dashboard/")

Where http://localhost:3000/dashboard/ would be a landing page on the front end

But to do this I would need to POST from the backend, to a listening API on the front end, which kind of feels wrong? Is this the wrong approach to take and should I use a more optimal method?

Obstruct answered 16/2, 2023 at 13:42 Comment(1)
Hi! What route did you end up taking? I’m in a sort of similar situation and was wondering about this too.Shavian
L
1

One approach could be to have the callback URL point to the front end instead. This callback would then make a second request to the backend with the information received from the OAuth provider for authentication Then the JWT token should be generated (or whatever you have for authentication).

OAuth

Liman answered 26/4 at 19:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.