Example needed for calling function with authorization headers

Hi.

Would anyone have an example of how to obtain the required authorization headers when calling an authenticated function from the front-end?

I understand the following is needed

Authorization: Bearer myJWT.accesstoken.signature
auth-provider: dbAuth
Content-Type: application/json

Along with a dbAuth cookie.

This is highlighted in the doco but I don’t know how the front-end can obtain the information for these headers.

Many thanks
Oide

May I ask that if this is an authenticated function and you are accessing it from the web side, why not simply make it a GraphQL service?

But, you can get the token etc from the useAuth hook just like you can deconstruct and get the login command, isAuthenticated check, currentUser etc.

See getToken here https://github.com/redwoodjs/redwood/blob/58a7a8fe7399f721408d4d1a7050a25f3ef81cef/packages/auth-providers/dbAuth/web/src/dbAuth.ts#L82

The cookie should be sent as part of the request like any other cookie assuming CORS is respected and it should be since dbAuth’s handler is just a function like this would be.

Be sure to pass the auth-provider in the header as per the documentation.

Hi
Thanks for your reply. I am calling an external rest based API from my function so I didn’t think a graphql service would be appropriate.

Hi. Thanks. I’ve figured out how to get the token using getToken and I am sending this in the request. However, since I am using dbAuth, I think I need to send the dbAuth cookie. Unfortunately I don’t know how to access the dbAuth cookie.

It’s completely appropriate.

The Prisma db is an sdk/client that interacts with external info — a database.

Using any other client/sdk that fetches or interacts with data like any other api is absolutely appropriate to be a service and part of your GraphQL api. In fact it’s encouraged.

Just custom write the sdl as a query and the type of the info it returns.

@oidebrett I recommend you read through this how-to: Using a Third Party API | RedwoodJS Docs

Especially the part on server-side-api-integration

Thank you David and Tobbe. I took you excellent advice and moved away from a function for my api call to using a graphql service. I actually took the opportunity of creating a database table to log apicalls per user so having a graphql service is a better choice. I now call my api from within my graphql service. Thanks a million for the direction.

Nice

Your addition of keeping a log/audit for the responses is a great one.

You can use to to do retries on failures or even cache the results and a timestamp and only refetch from the outside services wheb the data is stale to limit requests.

Glad it’s working well.