Hi, I am trying to authenticate connections to a MongoDB database using JWT tokens generated by Netlify Identity.
The MongoDB docs ask for the signing algorithm and secret key to verify JWT tokens passed in. How can I get this information for my Netlify Identity tokens?
Additional context in case it is needed:
I found you can manually set the secret key under Authentication Controls by paying for the Business Plan, but I rather avoid paying $99/month just for this.
The MongoDB database is being accessed through a Mongo Realm instance which generates a GraphQL API. That GraphQL API is accessed through Apollo, a React library. The whole flow works with authentication disabled, now it’s just a matter of securing it.
I have not explored using Netlify Functions for this because I want to stick to the GraphQL API. If anyone knows a way to proxy GraphQL queries through a Netlify Function as a form of security I’m happy to hear of those options.
Hey, I’ve gone through this thread before. My big question is how to actually implement a proxy in Netlify Functions, if you have any JavaScript examples I would greatly appreciate it.
One big concern I have is a GraphQL query may take longer than 10 seconds to run, but I don’t want the whole request to fail because the Netlify Function timed out waiting for MongoDB.
The proxy didn’t work, but I found a solution I’ll share for anyone who stumbles on this.
Mongo Realm allows for authentication with a custom function. The solution is simply to write a Mongo Realm function that calls a Netlify Function endpoint that checks if the user is authentic, and sends back the user’s ID if they are.
Netlify Functions have user authentication build into them. All you need to do is call
const { user } = context.clientContext;
in the Netlify Function to get the user, and it would be null if they’re not logged in. This also allows you to check for Roles or other custom logic to decide if that particular user should in fact be allowed to access MongoDB.
The only tricky part is Netlify Functions may not have the user token if you are calling them from Mongo Realm, so you will need to pass the user’s token to Mongo Realm, then have it include it as an authorization header when it calls the Netlify Function.
Thanks so much for coming back and sharing you solution! Knowledge sharing is beneficial to future members who encounter something similar, so we definitely appreciate it.