Authorizing access to resource in a REST API - rest

I am new to building API's and I am having trouble understanding how to perform the following task reasonably.
There is an endpoint:
/user/{user_id}
which retrieves the details of the user.
The frontend code will request this endpoint to get details about the user to display on the dashboard.
I have to protect this endpoint so that a user who doesn't represent this user_id, emulates the request to get information about other users.
Since REST based API's are sessionless, I cannot store session keys. So how do I make sure that the server sends the user information only if the owner of the user id has requested it?

You are right. HTTP is a stateless protocol, therefore REST inherits that quality too.
Here is the deal in simple words.
[REST client] -------> [API endpoint]
You have many REST clients, and you need to make sure that only authorized users will grant the access to your API endpoint. One solution as #James suggested is use a token mechanism such as JWT https://www.rfc-editor.org/rfc/rfc7519.
If you consider JWT authentication, the process flow will be as follows.
[REST client] -------> [AA service]-------> [API endpoint]
You will need an AA(Authorization, Authentication) service in the middle. For example in a microservices approach, this can be performed from a API gateway which is a gateway to all of your services.
Client will give AA service their username and password. In exchange AA service will give the client a JSON token signed only by the server so that the confidentiality is protected. This token contains 3 things.
Header which specifies the type of token and algorithms used to sign it
Payload which includes claims like to whom the token is issued, when should the token expire, what is issued user's role should be etc. (see https://www.rfc-editor.org/rfc/rfc7519#section-4)
Signature which a product of unsigned token signed by the server key
Then you encode each header, payload, signature with base64 and concatanate with a ".". You now have a JWT.
AA service returns this JWT in exchange for credentials.
Client should store this token securely (ex: local storage) and the communication medium should be encrypted(ex: TLS). See https://stormpath.com/blog/jwt-the-right-way#how-to-secure-jwt , https://www.rfc-editor.org/rfc/rfc7519#section-6
After that for every subsequent REST call, client should include the received token, preferably in the Authorization header although it is technically possible to send the token in the message payload as well.
Then it is AA service's responsibility to decrypt the token using its signing key evaluate claims in the JWT and act upon whether to authorize the API call send him HTTP 401,403 responses.

Related

When to validate JWT

I am building an application that spans over several parts of infrastructure.
An end-user can sign in to a portal using OAuth 2.0 authorization code flow. When calling different APIs, the portal requests tokens on-behalf-of the signed in user and attaches those to outgoing requests. The tokens received to call external APIs have an aud claim matching the target API.
When a call to an external API is fired, it first passes through an API Gateway. This API Gateway validates the token and ensures the aud claim is actually intended for this endpoint. It also verifies roles and a few other claims.
When the gateway checks pass, the request is forwarded to the actual implementation. Now the actual implementation also verifies the token, but only that the token is valid (e.g. not looking at specific claims). That is not to say that the claims aren't used internally in the application after the token is validated, roles are very much part of the application logic.
So to summarize this as bullet points:
User signs in to portal
User performs some action that causes an API call
Portal attaches token to outgoing request
Request hits gateway for 1..n claims are validated
Request is forwarded to actual implementation
Implementation again validates token is valid, not looking at claims
All endpoints are public, e.g. I could call any of these from anywhere as long as I have a token.
In the above outlined scenario, I'm handling the token properly?
In general, what is the recommendation for tokens passing through several layers of an application? Should every layer validate the token? If yes, are there exceptions to the rule?
Typically, JWT tokens are validated when are sent from the client-side to the server-side. As these tokens are signed, if anyone tries to tamper with the token before sending it to the server-side endpoint, the token verification will fail, therefore these tokens are a secure way of sending the session of an authenticated user to an API or a server endpoint.
These JWTs can be also transferred between servers or different application layers, and it always would be a good practice to verify the token before processing it. It is adding a layer of security to avoid anyone sending tokens to that layer directly and skipping the validation.

Mobile app authentication using Token based on OAuth2.0

I'm building a REST API using Elixir's Phoenix framework. In the API, I need to authenticate the user by phone number i.e., via sending an SMS OTP code. After authenticating the user, the Auth server sends the Access token and Refresh token to the client. The client(mobile app) stores those tokens locally and sends the Access token in the HTTP header as Authorization: Bearer <Access_Token> in every request to resource server. My actual question is, how do resource server validates the Access token that is received from the mobile app/client?
Does resource server needs to contact Auth server to validate the Access Token? That would a lot of overhead. Please help me understand RestFull API Authentication.
Thanks for taking the time to read my question.
It sounds like you have everything working up to validating the token. You are going to need the public key for the server that signed the token. It depends on what auth server you're working with on how you get that. In some cases you may be able to preload this key as a configuration setting on your backend. Otherwise you can probably get it via https request to the auth server. Most auth servers these days I expect to provide a JWKS api that you can use to get the keys you need. Then with the token and the public key you can use your elixir jwt library to validate that the token you have was signed by the server you trust, meaning the SMS code was validated, and you can proceed with whatever is needed in the backend to handle the request.
If you're using Joken for elixir you can review https://hexdocs.pm/joken_jwks/introduction.html and https://hexdocs.pm/joken/introduction.html for more information.
how do resource server validates the Access token that is received from the mobile app/client?
The same way a nightclub bouncer verifies your driving license as proof-of-age to let you in: by validating the authority and signatures, but it does not need to phone-up your DMV to verify that your license is real because it trusts the signatures (in this case, cryptographic signatures).
That said, some systems do use "reference tokens" which are short (say 32 bytes) of meaningless random data which are used as an unpredictable record identifier for some user-permissions record held by the authorization server. The resource-server will need to contact the auth server initially, but then it can simply cache the auth result itself for some time window.

registering a rest API with OAuth

I have written a web application which makes REST API calls to a message broker. The message broker contains already written REST APIs to which can be used to get message broker data. The message broker is written in a way in which each REST API call sends the user name and password which is encoded with base64. I need to make a login to my web app and authenticate it with OAuth.Does anyone know how to do this? How to authenticate the REST APIs with OAuth?
Step 1: Add OAuth 2.0 to your web server. This is very standard with lots of libraries available. You did not specify the Identity Provider that you will use (Google, Facebook, Auth0, Okta, etc), but each vendor has documents and libraries for you to use in your desired language.
Step 2: Add an Authorization Header to your API calls. The standard method is to add the HTTP header Authorization: Bearer access_token when making an API call.
Step 3: Add OAuth token verification to your API. When your API receives a request, it extracts the Authorization header and verifies the Bearer token. How this is done depends on the Identity Provider. For example, some vendors provide a Signed JWT (which you verify with the vendors public certificate), others provide an opaque access token (which you verify by calling the vendor's token endpoint). Add internal caching of tokens so that you don't need to verify on every API call.
If you understand OAuth 2.0 the above steps are straightforward to implement. If you don't Oracle has a set of videos which are excellent for getting started understanding OAuth.
Oracle Cloud Primers
If your desired OAuth implementation does not require users logging in and is a server to server service that you control on both ends, then you can use just part of OAuth which is Signed JWT (JWS). You create a Json data structure with your desired content and sign it with a private key. This creates a token that you can use in the above steps. You would then validate the token using your public key. You can use self-generated keypairs generated by OpenSSL or similar products for your signing and verification.

Facebook oauth2 - secure after-login use

I would like to ask little theoretically.
I have an angular6 + spring app that has its own client, app-specific client data.
These data can be divided into two groups
managment-data: Like client roles that allow client to visit different parts of app
client-data: personal settings, history of activities etc.
Because I would like to make login as user-friendly as possible, I would like to implement facebook login.
After user click "FB login button", facebook returns me some-user info and mainly a security token. How could I use this to securely communicate with my BE.
When someone sends request to BE, I need to be sure, that its the same person that logged in to facebook.
If I send this token as part of request, what stops possible attacker to somehow obtain token and then impersonate original user?
In what form I should send data I got from Facebook to my own server?
How should I work with token on server?
How can I validate its authenticity?
Thank you for answers
Filip Širc
You should look into the usage of OpenID Connect along with OAuth protocol. It allows you to authenticate the user to your client application (Angular6 + Spring app) to verify the user details.
When you are sending an access token to access a certain resource, you should avoid sending it as a request parameter. Usually it is encouraged to send it under the Authorization header of the request as a bearer token. However, if you want it to be extra secure, you could encode the token before sending so that it would be difficult to decode it and steal any valuable information.
Also, when you are sending sensitive information, it ise better to send them in the form of a JSON Web Token (JWT). You can use a third party library to create a jwt to include the information that need to be sent to the server. You can sign the jwt with your own signature which can be validated later. Refer https://www.rfc-editor.org/rfc/rfc7519 for detailed information about jwts.
You should use the claims in your access token to grant a user access to the resource you are protecting. Since most of the tokens are sent in the form of jwts, you can decode them and get check the necessary claims such as scopes, audience (client app), subject (user), etc.
Most importantly, you should validate the signature of the token sent from Facebook to make sure its an authentic one. For this, you have to get the public key details from Facebook's jwks endpoint and validate the signature using a third party library (auth0, nimbusds, etc.). Facebook's digital signature will be unique and this verification process is the best way to ensure the security. Also, you can check whether certain claims in the token match your expected values to validate the token. This can also be done through libraries such as ones mentioned above. Here's auth0 repo for you to get a general idea.

How to provide OAuth through services?

I have 3 services (in the real much more):
Authorization service (uses OAuth 2.0)
Frontend service
Resource service
and client (web-browser).
I store session_id, access_token and refersh_token in cookies of the user's web-browser. The user goes to Auth service, signs in and gets these tokens. After his web-browser is redirected to Frontend.
Frontend and Resource services can't validate tokens because they know a nothing about it, so they must make a request to Auth service.
The current scenarios:
The user (web-browser) sends a request to Frontend service, the Frontend sends a request to Auth service to validate access_token. If it's invalid the Frontend sends a request to refresh token using refresh_token.
If the Frontend needs an access to Resource service to process a request then the Frontend sends its client_id and access_token to Resource service. The Resource service sends a request to the Auth service to validate an access_token too.
Are my thoughts right? Or it has simpler schema?
P.S. All services use RESTful architecture.
OAuth talks about how the tokens be exchanged. What you have mentioned it seem liek you are talking about using implicit grant, which is little less secure and you may think of opting for authorisation flow.
Other than that, in microservices when you have many services and one user request pass through many downstream services, verifying the token with auth provider at each and every step might become a bottleneck.
There are ways out there by which you can skip this call to auth server and still validate the sanctity of the token without making an explicit call.
One way is to make use of JWT. These tokens are signed by the Auth provider and your services have keys which can help you validate if the token is modified on it way, and token itself has all the information you need to ensure validity of it, like expiry time, intended audience, clients, roles etc.
On login you get AT and RT. AT could be passed along to downstream for authentication and authorization and RT could be used when AT is expired.
You only need to talk to auth provider at the time of login and when you need to refresh the token.
You can read more about the JWT OAuth2.0 with JWT and OIDC to get more information around it