Finding out who currently authenticated user is

Hi all,

I am writing an endpoint on Servercode that only users with “AuthenticatedUser” role can use. In my server code, is there a way to know who the user who is hitting the endpoint is? Basically even while authenticated, I still want to make extra validations.

Contrived example:
Let’s say the user has a balance of dollars and I make a /addDollars endpoint that only authenticated users can use. Let’s say the endpoint takes a “dollars” and “username” parameters and adds dollars to a user with that username. If an authenticated user knows another user’s username, they could add dollars to their account… how would i prevent that? Is there some way to check if the “username” param matches the currently authenticated user’s username?

Hi Gal,

Is the server code in JS or Java?

Regards,
Mark

Hi Mark, as always, thanks for the quick response. I am using server code in JS

Hi Gal,

No worries, we’re glad to help.

In the context of a service invocation, your code gets access to “this.request.context”, which has the following properties:

    userId userToken userRoles
If one of the formal method arguments is "username", you should be able to do the following: fetch the user object using this.request.context.userId and check if the username in the returned object matches the one provided in the argument for the service invocation.

Hope this helps.

Regards,
Mark

works great, thanks. Though I believe what i needed was this.context.userId, not this.request.context.userId

Yes Gal. That is correct for 3.0

Just keep in mind, that in Backendless 4, it was moved to this.request.context (as Mark said), among with the http headers, query and path params