2

So I realized that one could gain access to the endpoint of an API of an angular 2 app just by viewing the XHR requests on the network tab in the dev. tools, and the token by logging console.log(localStorage.getItem('token')) to get access to the token. Is there anyway one could prevent this?

tobie
  • 121
  • 10

2 Answers2

1

I think there is no way you can avoid that issue as tokens always has exposed to client. The only thing you can do is just limit your token lifetime so client have to refresh token every N sec/min.

If you want to go even more hardcore with that approach you can set really short lifetime for your token so it will be practically expired like after each request. In that case if token gets stolen it just wont work if anyone try to access your api with that token. With that approach every time you access your api server you have to request a new token from a server. Also it could be achieved by server providing you a new token in header in each response as your app is a trusted client.

When you are building a solutions like that you have to be aware of XSRF and that Angular actually has a build in support for Cookie-to-header token that coming from HttpClientXsrfModule that you can use with HttpClientModule

Some useful resources:

angularrocks.com
  • 16,643
  • 10
  • 76
  • 96
1

There is no way you can prevent your user from viewing your token in a web request, but there are many ways you can secure it, such that it is not worth the time or energy to crack one single token. I would not consider it a security flaw if it is used correctly and securely.

Take JSON web token (JWT) for example, your token data is hashed with a secret key. If you pick your algorithm and secret key carefully, then it's basically impossible to crack the token within the token't lifetime (if you set expiration time).

In one of my projects using JWT, I also randomly generates a JWT ID (JTI) value with the token, and the JTI is also hashed with yet another secret key and saved as a cookie value that is httpOnly. That way, even if the JWT is compromised, it cannot be used with another machine or even browser because the JWT ID will not match.

Daniel H.J.
  • 418
  • 4
  • 9