Database or collection-level data access rules with custom JWT authentication

Hi,

We are building a multi-tenant application and we would like to store data related to different end users in the same cluster. The data for each user would be stored in their respective databases or collections in the same cluster. The data needs to be queried from a browser, each end user should only be allowed to access their own data.

We are using the custom JWT authentication because it allows us to pass an end-user id in the token. We configured the authentication to grab this id and store it in the user object.


Then we created a rule to allow each user to access documents that have this id

With this approach, we have to store the id in each document. This seems unnecessary, it will bloat out data and increase our data transfer.

Ideally, we would like to set a rule based on the database name or collection name. We would like to create this database or collection with the id and match it with one included in the JWT token.

Instead of our rule:

{
  "tenant_id": "%%user.data.tenant_id"
}

we would have something like:

{
  "%%database.name": "%%user.data.tenant_id"
}

We combed the documentation many times but I could not find such a feature. Did we miss something? Is there a better way to implement this?

Note: we are using serverless instances and the Web SDK.

Hi @MattB,

You are correct that there’s no way to represent this with the existing rules expansions. Feel free to file a feature request here: Atlas App Services: Top (238 ideas) – MongoDB Feedback Engine.

In the meantime, the scheme you are currently using is what we would recommend.

1 Like

Thanks for the quick answer!

I filed the feature request: Add expansion for database and collection in Rules Expressions – MongoDB Feedback Engine

Actually, I forgot to ask - are you trying to represent this in a default rule, or collection rule?

If you use specify roles for each collection independently (as opposed to default roles), you could instead hardcode the respective tenant_id in the role for each collection, and then you won’t need the field in your documents. This may be cumbersome to maintain, but you could come up with an automated workflow to generate the correct rules and deploy them to your app via the CLI, github integration, or admin API.

That’s a much better idea! Thanks!

I was able to use this rule:

{
  "%%user.data.tenant_id": "640c4af0-e748-4766-8bd9-b4b7e2fadcae"
}

If I can ask a follow-up question. We may have a case where a user has access to multiple tenants. So we tried to pass an array of tenant ids in the JWT token claims.
image

Is there a way to check if “640c4af0-e748-4766-8bd9-b4b7e2fadcae” is in the array stored in the user’s provider data? My attempts were unsuccessful. I think the user’s provider data is interpreted as a string and not an array.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.