I have a server in Express that exposes some APIs to a web application. I am looking for a good way to manage both final users and 3rd parties authentication.
Right now, when a user sign-up with email&password, the server generates a JWT associated to that user.
function createToken(user, role) {
var usr = {
role: role, // admin | customer | shop
email: user.email,
name: user.name
};
var expires = (Date.now() / 1000) + 60 * 60 * 24 * 365; // 1 year
var nbf = Date.now() / 1000;
usr['nbf'] = nbf;
usr['exp'] = expires;
var token = jwts.encode(usr, process.env.SECRET);
return token;
}
When the Web-Client receives that token, it stores the token in cookie/web_storage, and uses it for every API call to the server, and for the auto-log-in as well. The token contains also the role
, so when server receives a request, it knows if that user/role can access to the route/resource asked.
function checkToken(token, api_name) {
// verifies secret and checks exp
jwt.verify(token, process.env.SECRET,
function (err, decoded) {
if (err) { throw { msg: "token expired or not authenticated", code: errors.ERR_NOT_AUTH }; }
else {
var role = decoded['role'];
return does_role_can_access_api(role, api_name); // true or false
}
});
}
Now some 3rd parties want to access to some of my APIs. I want to create an Express-Gateway to make api-keys for applications that wants to use my server, and keep existing JWT authentication for single users.
So I will have
|----------------|
| my Web-App |
|----------------|----> |------------| |------------|
| Express | | my Server |
| Gateway |----------> | APIs |
|----------------|----> |------------| |------------|
| 3rd party |
|----------------|
- My Web-App, should access to all the APIs, because my Web-App is used
by
admin
s (like me), and by our users (customers
andshops
). - 3rd party Apps, should access only to some APIs, since they will be
only
customers
andshops
.
So I want to make something like this:
|----------------|
| my Web-App |
| scopes: |
| [admin, user] |
| |
|----------------|----> |------------| |------------|
| Express | | my Server |
| Gateway |----------> | APIs |
|----------------|----> |------------| |------------|
| 3rd party |
| scopes: |
| [user] |
|----------------|
At the end, my Web-App will have an ApiKey with all the scopes, while 3rd parties ApiKeys will have just user
scope, so I can filter routes on that. Single real users, regardless to the App used, will use the JWT token to log-in and make requests.
So every request will have an ApiKey (based on the Application used) and a JWT Token (to identify the user):
- The ApiKey will be added to the header by the 3rd party server,
- The JWT Token will be (retrieved and) added to the header by the web_storage of the User's Browser.
Does it sound good?