Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Securing API Key in Angular2

I've been googling more than a day now. May be I'm missing the correct keywords.

I have the following setup:

  • ExpressJS API (running with pm2 on port 3000)
  • Angular2 app - served via nginx

Both run on the same server.

Calls to the api (mydomain/api/) are proxied to 127.0.0.1:3000

For api calls which require authorization I will use JWT and user authentication.

What I want to achieve is that I generate a token for my angular2 app which is allowed/required to make the public calls (listings of products for example).

This token needs to be transferred securely of course as I don't want others obtain my products and prices via direct api calls (with a stolen token).

Any help appreciated.

like image 549
user1261284 Avatar asked Nov 09 '22 20:11

user1261284


1 Answers

First, as @eesdil said, you must use HTTPS. In that case, all your calls are encrypted and safe.

In my example ( Angular 2, Express and JWT ), i used crypto module with pbkdf2 algorithm for hashing passwords.

This is workflow:

  • /login/signup -> hash password and generate salt -> store it on server
  • /login -> validate password against stored one -> generate jwt -> save it in localStorage on client
  • /api -> send jwt in Auth header -> validate on server -> send response

Working example is here: https://github.com/vladotesanovic/angular2-express-starter

like image 112
Vlado Tesanovic Avatar answered Nov 15 '22 05:11

Vlado Tesanovic