Adding Custom Claims

I’m trying to add a custom claim to my Auth0 API but I am struggling to understand the documentation on this. Let me explain what I would like to do:

I want to add a simple integer claim called DatabaseId. When the user logs in on the front end using the stock Auth0 login screen, the front end will redirect him to a screen where he can choose which database he wants to log into (a user can have access to many databases). Once he picks a database, I want to save the selected database ID as part of the access token, so that every time the front end performs a request on the Web API, it sends along (within the access token) the chosen database ID. The Web API controller actions will then be able to read this database ID off the access token, and know which database to perform the various database queries against.

I was going to save the user’s chosen database in a global variable in my Web API (a dictionary of type ) but someone told me that global variables are a bad idea, and I should rather send the chosen database id in the access token with every API call.

So I’m guessing I need to add a custom claim in Auth0 for the API? Then once the user logs in, and selects which database he wishes to connect to, my Web API can programatically set the selected database id using Auth0’s Management API? Then all further calls to the Web API by the front end should include the selected database ID in the access token? Is my logic correct or am I completely lost? :confused:

If my logic above is correct, could someone please give me a pointer on how to add this “DatabaseId” custom claim to Auth0, so that it is sent in the access token with every call to the Web API by the front end? Thanks…

I might be missing something, but it may not make sense to tie the access token to a specific database. In particular, why have you discarded the possibility of including the database identifier as part of each request, but outside the access token.

The above would even allow the flexibility for the end-user to select another database without you having to now obtain a different access token. In general, including possibly volatile information such as which target database the user is currently working against in the access token may lead to a more complex implementation because now you need an access token for each database switch.

Unless the process to validate that a user has access to a given database is really complex and you don’t want to perform it in every request I see little reason to push the identifier inside the access token itself.

Finally, you can add custom claims as part of the authentication/authorization transaction, but you’re only asking the user for the database identifier after he has logged in and returned to your application so that would make this really complex because at that time the tokens have already been issued.