1

I have a spring boot backend which can send jwt token on login. I need to implement these features in my Astro frontend:

  • Redirect to /login if no token is found in local storage
  • On login retirieve the token from server response and store it in localStorage
  • if any of the requests sent to server return 401 (unauthorized) which will mean token either expired or is not correct -> delete token from localstorage and redirect to /login
  • token should be sent with every request in headers: Authorization: Bearer

There is little to no documentation about this for Astro specifically. I have implemented the same thing with my old vue project using store and mutations but I did not find anything remotely simillar with astro though.. Here is the project file I was referring to: https://github.com/salat-23/wafflesproject-frontend/blob/master/src/store/index.js

P.S. I am not a front end developer and dont know a lot of things so any help and tips will be appreciated!

salat _
  • 91
  • 1
  • 7
  • Did you find anything useful between Astro.request, Astro.response, and Astro.redirect()? – thdoan Jun 03 '23 at 09:39
  • 1
    Update: I just discovered this PR: https://github.com/nextauthjs/next-auth/pull/6463 -- exciting! – thdoan Jun 04 '23 at 17:27

1 Answers1

2

I've implemented Token-Based Authentication in a Astro project using ServiceWorkers.

With a ServiceWorker you will be able to create a fetch event handler that will be called for every request your frontend sends. In this handler you can redirect, add auth headers and store tokens.

Since Astro is a Multi-page application framework, this is the only solution to your problem that I know of. Token-Based Authentication is easier to implement in a Single-page application like NuxtJS

This is my ServiceWorker for a Astro project.