Home > database >  Golang - Server Side Login Handling - how to resume request after login?
Golang - Server Side Login Handling - how to resume request after login?

Time:12-14

Currently, I’m developing a web app with server-side rendering using the Gin framework and I’m having a problem with login intercepting. When an HTTP GET request hits an endpoint, middleware is used to check the browser cookie and redirect the traffic to the login page. This works fine and after successful login, the user is always redirected to the dashboard page. My question is how I should redirect the user back to the originally requested URI instead of the dashboard page?

Also, a bit more complex scenario is on HTTP POST. It looks like the HTTP POST method doesn’t work quite well with a redirect. Also, how would I resume the request with the same post request after the user successfully login?

Thanks for the help!

CodePudding user response:

For the HTTP GET scenario, this one is easy, you need to remember the original URL somewhere. The are a few ways you could go about this:

  1. Store the URL in session information(if any is available, you do need sessions for non-authenticated users)
  2. Store it in a query string, for example, redirect to example.com/login?original=https://example.com/another-page. Your login page can look for the query parameter and include it in the login form or make sure that the action of the login form matches the given URI. On a successful login attempt you can get the original URL form the query param and set it as the Location.
  3. Store the original URL in a cookie, upon successful login you can just check the cookie value and use that.

As for the HTTP POST scenario. If you just want to redirect the same POST request to a different URL you can use a 307 Temporary redirect. A 307 will preserve the request body and method and not turn it into a GET request like a 303 See Other or 302 Found.

Resuming the original POST after showing the login screen and after a successful login is a little more complex. When you redirect to the login page you interrupt the flow of the user, maybe it is better to let the user re-post their request after logging in, instead of doing it for them.

Having said that, it is technically possible. We require two steps, first is storing all the data to recreate the request. Then after login completion we can render a form with this saved data and use javascript to submit the form. By adding:

<script>document.getElementById("myForm").submit();</script>

After your form, the browser will submit the form after loading the javascript, thus recreating the original POST.

The storage part can be done via the server side session or a cookie.

  • Related