Search code examples
reactjslaravelrestaccess-token

How to Secure API access_token (React, Laravel)


I am working on an application (Frontend: React, Backend: Laravel). When I make a login request I get access_token from the Laravel server. I save this access_token in localStorage.

Now the problem is that anyone can see the access_token in developer tools in the browser. access_token is also visible in request headers.

enter image description here

If a user is not on his seat for some time, then some other user can steal this access_token and paste in his browser and now that other user will be able to access the application as the first user. Further I have seen some discussion on other websites that localStorage is prone to XSS attack.

My question is that where this access_token should be stored. If I save access_token in some javascript variable then access_token is lost when the user closes and reopens the browser or user refreshes the page. And he will be asked to login again, which is bad for user experience.

How can I protect access_token from unauthorized access? What are the best practices?


Solution

  • Although, this type of hijacking is possible in facebook and other websites as well but Here are few suggestions

    Option 1

    1. Make some landing page for your actual application.
    2. Add some button on that landing page to open actual website with some dynamic token authentication with restricted browser options by opening new window with javascript e.g.

      www.yoursite.com/secure_login?abc=3jfj834y7827875448548hffhjdhfd8

    3. On direct browsing of link (www.yoursite.com/secure_login) give error. Your dynamic token will serve as session key etc. It is just like CSRF functionality.

    4. Disable Right-click and F12 on your website.
    5. Don't open your website if java-script is disabled in browser settings. So force user to enable java-script first.
    6. It is very difficult to go inspect-element now.

    Option 2

    1. Make multiple access_token like keys with honey-spot names e.g. security_key, authourization_token, access_token, login_session etc. Your actual key must be different from default keys used globally in web frameworks.
    2. Initialize them with some random values and by applying some encryption like sha256 etc.
    3. Use refresh token concept as your session string will be continuously refreshing and changing
    4. Check if any of these tokens missing while making request then block that IP for some time (Like Login throttling for brute force attach prevention)
    5. Now this way if you have let say 12 keys with only one or two actually used its difficult to get all variables (like you mentioned if user is away from seat for sometime) and you can fool them with multiple names.
    6. You can even actually use these multiple sessions
    7. You can also decrease expiry time