Hi,
I am struggling nearly all day to get authentication to work on custom lambda functions.
My fetch won’t add cookies and therefore authentication is not working. I have tried to set access policies and credentials on both web and api side, taking graphql api calls as a reference. But my function is not able to access context.currentUser, since Cookies are missing. If I copy them from a graphql to my custom function fetch, it works.
Since my web and api side run on different sub domains I also tried to set the cookie Domain value to the domain. However, when I am doing this, the user cannot be logged in anymore. I also tried using SameSite ‘Lax’ as property. But somehow reauthentication does not get a new token and therefore does not sign in.
Web
fetch(window.RWJS_API_URL + '/myFunc', {
method: 'PUT',
headers: {
...fetchConfig, // taken from useFetchConfig
'Content-Type': 'text/plain',
},
credentials: 'include',
mode: 'cors'
body,
})
Api
(use of middy is not necessary i think. I tried all kinds of options)
const myFunc = async (event: APIGatewayEvent, context: Context) => {
if (isAuthenticated()) {
// not reaching this part
} else {
logger.error('Access to myFunc was denied')
return {
statusCode: 401,
}
}
}
export const handler = middy()
.use(cors({ credentials: true, origin: '*' })
.handler(
useRequireAuth({
handlerFn: myFunc,
getCurrentUser,
authDecoder: createAuthDecoder('session'),
}))
Auth-Cookie Settings
cookie: {
name: 'session',
attributes: {
HttpOnly: true,
Path: '/',
SameSite: process.env.NODE_ENV === 'development' ? 'Lax' : 'None',
Secure: process.env.NODE_ENV !== 'development',
Domain: process.env.NODE_ENV === 'development' ? 'localhost' : 'myDomain.com'
},
}
I am working on a serverful environment using dbAuth.
I am wondering if there is still a piece that I am still missing. Currently I think the issue is the failing reauthentication on login. auth/getToken returns statusCode 200. I am not sure how this is connected to the Domain setting. Without the Domain setting login seems to work, but custom functions do not.
Btw. I tried to add some documentations on custom functions, because it is quite vague in some situations.
Error when calling backend throws at authEnrichedFunction. This seems to happen already on network request with method OPTIONS which should be the preflight:
2024-12-06T17:02:15.506919651Z {"level":50,"time":1733504535506,"reqId":"req-2n","err":{"type":"UnauthorizedError","message":"Unauthorized","stack":"UnauthorizedError: Unauthorized\n at myFunc (/app/api/dist/functions/myFunc/myFunc.js:114:11)\n at authEnrichedFunction (/app/node_modules/@redwoodjs/graphql-server/dist/functions/useRequireAuth.js:59:20)\n at process.processTicksAndRejections (node:internal/process/task_queues:95:5)","status":401,"statusCode":401,"expose":true},"msg":"Unauthorized"}