Skip to content

API Gateway

Anthony Genson edited this page Apr 29, 2018 · 2 revisions

API Gateway

When doing an HTTP request on the API, it will first go through the API Service Gateway. It is here that we will do the main authentification process, before anyone access to the other functions of the API.

Roles & Authorization

We can choose which routes need authentification or not, and define who can access to it. For that we have authentification and roles attribut for each route:

...
roles: ["ADMIN", "USER"],
authorization: true,
...

Route Exemple

{
	bodyParsers: {
		json: true,
	},
	path: "/admin/",
	roles: ["ADMIN"],
	authorization: true,
	whitelist: [
		"users.*"
	],
	aliases: {
		// Users: Actions on Users that needs priviledges
		"GET users/count": "users.count",
		"PUT user/change/role/:username/:role": "users.changeRole",
		"DELETE banish/:username": "users.banish",
		"DELETE users": "users.removeAll",
	}
}

Token Verification

When requesting an authorization for one route, the service will automatically search for the authorize function. It is in this function that we will check the given token (if there is one) and check if the role correspond to the ones define for the route.

Property Description
ctx Will serve to call a service action: ctx.call
route The route Oject that a user is trying to access
req The incoming request
authorize(ctx, route, req) {
	var authValue = req.headers["authorization"];

	if (authValue && authValue.startsWith("Bearer ")) {
		var token = authValue.slice(7);

		return ctx.call("auth.verifyToken", { token })
			.then( (decoded) => {
				if (route.opts.roles.indexOf(decoded.role) === -1)
					return this.requestError(CodeTypes.AUTH_ACCESS_DENIED);

				ctx.meta.user = decoded;
				ctx.meta.user.token = token;
			})
			.catch( (err) => {
				if (err instanceof MoleculerError)
					return Promise.reject(err);

				return this.requestError(CodeTypes.AUTH_INVALID_TOKEN);
			});

	} else
		return this.requestError(CodeTypes.AUTH_NO_TOKEN);
}

If this function does not return any error, then the user is now logged and the request will continue.

The information about the logged user will be stored in ctx.meta.user (accessible at anytime with ctx).