I have a question about RESTful APIs and security in a multi-tenant environment.
Imagine you have an endpoint: api/branches/:branchId/accounts/:accountId
Authentication is done through Bearer Tokens (oauth2). Each token includes a set of claims associated to the invoking user. A branchId claim is included in the token, and each user belongs to a single branch.
The security restrictions are the following:
The branchId of the GET request should match the one stored on the token claim.
accountId should be a valid account inside the branch identified by branchId.
The question is: which of the following solutions is correct?
Maintain the endpoint: api/branches/:branchId/accounts/:accountId. And do the required security checks.
Change the endpoint to: api/accounts/:accountId, obtain the branchId from the token, and then do the remaining security checks.
The application is meant to be multi-tenant. Each branch is a tenant, and each user may only access the information associated with its single branch.
Thanks!
I needed to make a decision fast, so I will be using solution 1. If anybody has an argument against or in favor please join the conversation.
Arguments in favor:
I totally agree with this answer: https://stackoverflow.com/a/13764490/2795999, using the full URL allows you to more efficiently decide which data store to connect with, and distribute load accordingly.
In addition you can easily implement caching, and logging because the full url is descriptive enough.
Independency of security and API. Today I am using OAuth2 but perhaps tomorrow I can send the request signature, and because the URL has all the information to fulfill the request it will work.
Arguments against:
Information redundancy: the branchId is on the URL and encrypted on the token.
A little more effort to implement.
Related
I have a problematic and a potential solution and i'm wondering if it's a good solution or if a better way of doing things exists.
I have an API A called by a frontend with a JWT token.
If the service doesn't have the solution I would like this service to fetch the solution from another API B.
Is it a good idea to forward the JTW token I received from the Front User and authenticate to the API B as this user to request my data (knowing that the JWT may carry useful information) ?
Should I maybe drop the JWT and authenticate in a different way to this API ?
Is there an industry standard for theses kinds of things or good pratice?
JWT access tokens are designed to be forwarded between APIs. Doing so maintains an auditable user identity. Each API then verifies the JWT signature, issuer, audience, scopes and claims. This is sometimes called a zero trust API architecture - but there are caveats.
SCOPES
Design these in terms of areas of business data. Eg client has scopes orders shipping and calls an Orders API. The Orders API can then forward the JWT to the Shipping API. Each API must check for the scopes it needs.
SAME TRUST LEVEL
As always, you need to think about threats. My above recommendations are for APIs split into microservices, often for technical reasons, eg smaller code sizes and multiple development teams.
DIFFERENT TRUST LEVELS
Consider forwarding a JWT to a Shipping API in a subdivision of a large company. You may not trust to give them the orders scope. In that case, use token exchange to get a new token with only the shipping scope, then forward that to the upstream API.
SUMMARY
Always aim to forward a JWT that maintains an auditable user identity. Use scopes as one ingredient to ensure least privilege. Also evaluate threats, to prevent potential exploits.
The main our product is Public API. We use IdentityServer4 for the authentication and authorization of our users. Now I'm fighting with my teammates about the number and type of information that can be in claims in token. For instance, usually, we add the user identifier and the identifier of user's organization in claims.
Also, we add user's configuration, such as
server URL where the user was provisioned
internal identifier of the user
user's device identifier
These user's configuration properties are requested from different internal services and databases during authorization and generating JWT tokens.
There is an option - keep in JWT token only the user identifier and request all configuration properties in the API method.
The main pros of keeping configuration in claims from my point of view are decreasing requests to other services and to the database.
Perhaps, there are best practices about my question from reliable sources or even in RFC what the information can be in claims?
There are no RFCs or standards which would say what information can end up in claims and which don't. I would try to stick to those guidelines:
Try to keep information in tokens as minimal as required. Don't put something in claims only because maybe one service will need it from time to time. Put only those claims which most of the service use all the time, or information which needs to be asserted by the Authorization Server. The other data usually belong to the microservices themselves or can be easily obtained through API calls. This is especially important if you're using JWTs publicly available on the Internet, as anyone can read those information.
Try not to put Personally Identifiable Information in a JWT, especially if the token is available publicly. When someone steals such a token they will be able to read your users' PII. If you need this kind of information in a token, then think of using the Phantom Token pattern. This way the information is safe from eavesdroppers.
By limiting the amount of claims in a token you can also limit the permissions of a token. It's better to have tokens with lower permissions and use token exchange whenever more information or privilege is needed.
Remember that the claims in the token are a contract between the Authorization Server and the consumer (usually the API). Once you add something to a token, you usually won't be able to remove it, as this will constitute a breaking change.
Have a look at these articles we wrote at Curity to get some more knowledge about dealing with claims and JWTs:
Claims Best Practices
JWT Security Best Practices
For most client applications and UI approaches JWTs seem to be a good way to carry tokens for an OAuth based approach. This allows decoupling of a User/Auth service and the services that are actually being accessed.
Given this architecture
My question is: in the case of public APIs (ie Github or Slack) where a bearer key is generated with specific roles. How is that key authorized in a microservice architecture? Do those types of keys just require that the Auth service gets queried with every request?
Could an API gateway mitigate this? I would like to understand if a solution exists where there is minimal communication between services. Thank you!
Normally, this is solved using scopes. The scopes are permissions given to a user to do certain operations,for example there will be a scope for read a repository, another for update it, another one for delete etc..
These scopes are tied to the token and normally are requested by the user himself or added automatically depending on the user type. And the same as the authentication process, they could be included in the token itself coded as a claim in a jwt or they could be requested or checked by calling an oauth server when one operation is requested.
The advantages of include them in jwt is that there is not need to call an external server every time an operation is requested so there is a lower latency and less bandwith is required, also you remove a point of failure. Obviously if this solution is used the token must be properly signed or even encrypted to avoid possible manipulations.
However it has also drawbacks, and the most dangerous one is that the token cannot be revoked because this information cannot be included in the token and the service that check if the token is valid only can access the data contained in the token itself. Because of this, this kind of tokens are normally issued with a little expiry time so in case of the token is stolen, the validity of it will be very limited
I'm extremely confused on how to use a centralized IDP with both authentication and authorization. The architecture for my project was to be a single web API and one React client. I wanted to keep things structured out into microservices just to try something more modern, but I'm having major issues with the centralized identity, as many others have.
My goal is fairly simple. User logs in, selects a tenant from a list of tenants that they have access to, and then they are redirected to the client with roles and a "tid" or tenant id claim which is just the GUID of the selected company.
The Microsoft prescribed way to add identity in my scenario is IdentityServer, so I started with that. Everything was smooth sailing until I discovered the inner workings of the tokens. While some others have issues adding permissions, the authorization logic in my application is very simple and roles would suffice. While I would initially be fine with roles refreshing naturally via expiration, they must immediately update whenever my users select a different tenant to "log in" to. However, the problem is that I cannot refresh these claims when the user changes tenants without logging out. Essentially, I tried mixing authorization with authentication and hit a wall.
It seems like I have two options:
Obtain the authorization information from a separate provider, or even an endpoint on the identity server itself, like /user-info but for authorization information. This ends up adding a huge overhead, but the actual boilerplate for the server and for the client is minimal. This is similar to how the OSS version of PolicyServer does it, although I do not know how their paid implementation is. My main problem here is that both the client and resource (API) will need this information. How could I avoid N requests per interaction (where N is the number of resources/clients)?
Implement some sort of custom state and keep a store of users who need their JWTs refreshed. Check these and return some custom response to the caller, which then uses custom js client code to refresh the token on this response. This is a huge theory and, even if it is plausible, still introduces state and kind of invalidates the point of JWTs while requiring a large amount of custom code.
So, I apologize for the long post but this is really irking me. I do not NEED to use IdentityServer or JWTs, but I would like to at least have a React front-end. What options do I have for up-to-date tenancy selection and roles? Right when I was willing to give in and implement an authorization endpoint that returns fresh data, I realized I'd be calling it both at the API and client every request. Even with cached data, that's a lot of overhead just in pure http calls. Is there some alternative solution that would work here? Could I honestly just use a cookie with authorization information that is secure and updated only when necessary?
It becomes confusing when you want to use IdentityServer as-is for user authorization. Keep concerns seperated.
As commented by Dominick Baier:
Yes – we recommend to use IdentityServer for end-user authentication,
federation and API access control.
PolicyServer is our recommendation for user authorization.
Option 1 seems the recommended option. So if you decide to go for option 1:
The OSS version of the PolicyServer will suffice for handling the requests. But instead of using a json config file:
// this sets up the PolicyServer client library and policy provider
// - configuration is loaded from appsettings.json
services.AddPolicyServerClient(Configuration.GetSection("Policy"))
.AddAuthorizationPermissionPolicies();
get the information from an endpoint. Add caching to improve performance.
In order to allow centralized access, you can either create a seperate policy server or extend IdentityServer with user authorization endpoints. Use extension grants to access the user authorization endpoints, because you may want to distinguish between client and api.
The json configuration is local. The new endpoint will need it's own data store where it can read the user claims. In order to allow centralized information, add information about where the permissions can be used. Personally I use the scope to model the permissions, because both client and api know the scope.
Final step is to add admin UI or endpoints to maintain the user authorization.
I ended up using remote gRPC calls for the authorization. You can see more at https://github.com/Perustaja/PermissionServerDemo
I don't like to accept my own answer here but I think my solution and thoughts on it in the repository will be good for anyone thinking about possible solutions to handing stale JWT authorization information.
I'm trying to follow OpenID Connect best practices. For the simple scenario of calling API from application the OpenID Connect suggest to pass the Access Token (which is not included user identity), and if the API in some points need the user identity it should call /userinfo endpoint of OpenID Connect provider.
So the question is: Is it the best way to get the user identity in API?
Assume I have an end point named CreateOrderForCurrentUser() so each time any user call this api I need to call the /userinfo endpoint, it seems too much cost for calling an api.
Why I don't pass the Identity token to the API?
Or Why I don't put some identity claims in Access token?
Should I use HOK Token instead of Access token?
Any idea please.
It seems here is kind of same as my question: Clarification on id_token vs access_token
And he respond in comments: https://community.auth0.com/t/clarification-on-token-usage/8447#post_2
Which as my understanding means: put some identity claims in Access token (Custom Claims) and rely on that in the API.
But still it doesn't make sense. The OIDC insist to not use Access token as Identity and now we are going to add identity claims inside Access Token. Could any one clarify that?
ID_Token is used for your client app tells the app who you are , the audience of the ID Token is the id of your client app , with access token , API/resource knows whether authorized to access the API and perform specific actions specified by the scope that has been granted.
By default , it will include user identifier in access token(sub claim) , so you should know which user when calling CreateOrderForCurrentUser function . You could customize the access token to include more user related claims if needed . But i would suggest to simplify the access token , and you could use access token to acquire user information by invoking user's API endpoint .
I asked the same question in Auth0 Community and there is a discussion about it that might be helpful for others who have the same issue.
I copy the same answers here:
markd:
You are correct that you should not use an access token as proof of identity, but before you get to your API you should have already authenticated the user and received an id_token for them. If you have already authenticated the user via OIDC, as far as I know there’s nothing wrong with adding custom claims to the access token to pass data to your API. Your API could also use the client credentials grant type to pull data from Auth0.
Me:
I’m looking for the best practices. I want to be sure adding identity claims to the access token and rely on that in API does not broke any thing and is based on best practices or maybe the best practice is always call the /userinfo endpoint in API and don’t rely on Access token identity claims.
The API doesn’t know about the authentication process and don’t care about that. Any one any how pass the signed Access token to the API, it would be accepted. Now in API point of view is that proper way to rely on identity claims in Access Token? I have doubts. But I would be happy if we could ignore calling the /userinfo end point each time.
jmangelo:
I can share some (hopefully) informed views on this subject, but please do take them with a grain a salt and question stuff you disagree with or you don’t consider clear enough. When it comes with software the devil is on the details and in the security landscape it’s even more true so you need to consider best practices as what will likely be recommended for the majority of the scenarios and also what will likely be less risky; it does not mean that nothing else is possible.
For example, although the recommendation is indeed to use access tokens in requests to API’s this does not mean that there isn’t a specific scenario where technically it would also be okay to send an ID token instead.
Focusing on your particular questions and starting with the last one (3); we should not compare HOK and access tokens because they are not at the same level. In other words, you could question if in your scenario you should use bearer tokens or HOK tokens as this way and using the terminology of your linked page you would be choosing between two token profiles where each give you different characteristics.
At this time, the access tokens issued by the Auth0 service as part of API authorization are bearer access tokens so this question has only one answer if using the Auth0 service.
Jumping to the first question; it’s not that you cannot pass the ID token to the API, it’s just that the scenarios where that would be adequate are much more constrained. For example, an ID token is issued with the client identifier as the audience; it’s common to have multiple client applications so you have just coupled your API to how many client applications you have, because assuming you will validate the audience of the ID token, your API would now need to know the identifiers of every client.
For question (2) which I assume is also interested in why call /userinfo if you can include claims in the access token. I believe this can depend a lot on requirements and/or personal preferences. At this time the only format supported when issuing an access token to a custom API is the JWT format.
The above means that you have a self-contained token that once issued the API can mostly validate independently which is great in terms of scalability because the API does not need to make (frequent) external calls for validation purposes.
However, being self-contained this immediately means that any data you include directly in the token will be considered the truth for the lifetime of the token itself. If instead the API is calling /userinfo or even the Management API directly then you ensure fresh data at the cost of network overhead.
In conclusion, in my personal view the choice between network calls and embedded claims is more tied to the characteristics of the data you are interested in that just from a best practices point of view.
As a final note, even without any addition of custom claims an access token issued by the service in association to a custom API already conveys user identity. In particular, given the access token is a JWT, the sub claim will contain an identifier that uniquely identifies the end-user that authorized the current application to call the API on their behalf.