How can I make this custom authentication work?
Unanswered
English Lop posted this in #help-forum
English LopOP
I have a separate backend written in C#, and that has a controller than handles the OAuth token exchange with another system, creates a session record in my database, and stores the sessionId in an HttpOnly cookie. Middleware looks for the cookie and grabs the session information from the database.
Unfortunately, I'm afraid I didn't think this through properly before starting to implement this. The authentication logic works correctly working with my APIs directly, but I'm not sure how to make it work with server-side API requests from Next since my cookie will not be included with the request.
I'm not really looking for code, but I'd appreciate any suggestions on how I can modify my approach to make this work.
Unfortunately, I'm afraid I didn't think this through properly before starting to implement this. The authentication logic works correctly working with my APIs directly, but I'm not sure how to make it work with server-side API requests from Next since my cookie will not be included with the request.
I'm not really looking for code, but I'd appreciate any suggestions on how I can modify my approach to make this work.
2 Replies
English LopOP
I'm not sure if this is an ideal solution, but it seems to work. I created a new
backendFetch
function to pass my SessionId cookie along:export const backendFetch = async (relativeUrl: string, init?: RequestInit): Promise<Response> => {
const headers: HeadersInit = {};
const cookieStore = await cookies();
const sessionCookie = cookieStore.get('SessionId');
if (sessionCookie) {
headers.Cookie = `${sessionCookie.name}=${sessionCookie.value}`;
}
const requestUrl = `${process.env.BASE_API_URL}${relativeUrl}`;
const response = await fetch(requestUrl, {
...init,
headers: {
...init?.headers,
...headers
}
});
return response;
};
To integrate with backend, you need to pass the headers and use api Requests either directly from frontend or through server side functions.
I'm unsure what you exactly mean by your question
I'm unsure what you exactly mean by your question