redux-toolkit icon indicating copy to clipboard operation
redux-toolkit copied to clipboard

RTK Query: Sending Authorization returns 400 Error

Open Devashree opened this issue 1 year ago • 1 comments

Hello I am new to RTK Query I read several articles around how to use RTK Query to send Headers. I am trying to do something similar:

const baseQuery = fetchBaseQuery({
  baseUrl: getEndpoint(),
  prepareHeaders: (headers, { getState }) => {
    const state = (getState() as RootState)
      const accessToken = state.authToken?.accessToken;
      if (!headers.has('Authorization') && accessToken) {
      headers.set('Authorization', `Bearer ${accessToken}`)
    }
    console.log('access Token',headers);
    return headers
  },
})

const baseQueryWithReauth = async (args: string | FetchArgs, api: BaseQueryApi, extraOptions: {}) => {

  const result = await baseQuery(args, api, extraOptions);
  console.log('result is',result);
  return result
}

export const workspaceApi = createApi({
  baseQuery: baseQueryWithReauth,
    endpoints: builder => ({})
})

whenever I try to append Authorization headers to the request it returns 400 Error . I tried to print headers it returns Headers {} . But I can see in the network log Authorization Bearer is sent returning Bad Request 400 Error. Please suggest. I tried to use same request from postman with same authorization Header the request is successful. Console Log: emptyHeader

Http Request returns 400 Error:

consoleRequest I tried to hardcode Authorization HEader still 400 Issue Persist.

Please note I am using rtk-query-codegen-openapi to call Bff and the class looks something like :

import { workspaceApi as api } from '../query/workspaceApi';
const injectedRtkApi = api.injectEndpoints({
  endpoints: (build) => ({
    getCandidates: build.query<GetCandidatesApiResponse, GetCandidatesApiArg>({
      query: () => ({ url: `/api/testBooking/getCandidates` }),
    }),
})

Devashree avatar Jun 15 '24 02:06 Devashree

@phryneas pls suggest

Devashree avatar Jun 15 '24 02:06 Devashree

You may need to pass credentials: "include" as an argument to fetchQueryBase (that's what I have on mine):

const baseQuery = fetchBaseQuery({
  baseUrl: getEndpoint(),
  credentials: "include",
  prepareHeaders: (headers, { getState }) => {
    const state = (getState() as RootState)
      const accessToken = state.authToken?.accessToken;
      if (!headers.has('Authorization') && accessToken) {
      headers.set('Authorization', `Bearer ${accessToken}`)
    }
    console.log('access Token',headers);
    return headers
  }
})

You may also need to configure CORs server-side to permit credentials as well.

rwilliams3088 avatar Sep 01 '24 06:09 rwilliams3088