如何将 Redux RTK 查询与 aws API 结合使用或将 RTX 与 Aws cognito json 令牌集成?

问题描述 投票:0回答:2

我正在尝试将 RTK 查询与 aws API 请求集成。我不需要使用 api 请求,但我需要使用 Cognito 提供的身份验证。

我尝试以这种方式集成,但显然没有添加令牌:


import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

// Define a service using a base URL and expected endpoints
export const researchApi = createApi({
    reducerPath: 'researchApi',
    
    baseQuery: fetchBaseQuery({ baseUrl: process.env.NEXT_PUBLIC_API_RESEARCH }),

    prepareHeaders: async (headers) => {
        headers.set('Authorization', (await Auth.currentSession()).getIdToken().getJwtToken());
        return headers;
    },

    endpoints: (builder) => ({
      getResearch: builder.query({
        query: () => `research`,
      }),
    }),
  })
  
// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetResearchQuery } = researchApi

知道如何让两者一起工作吗?使用 aws API 发送请求,或者将 json 令牌传递给请求的方法也可以。

干杯!

reactjs redux aws-api-gateway amazon-cognito
2个回答
1
投票

所以我做的prepareHeaders是错误的,这里有一些工作代码:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { Auth, API, Storage } from 'aws-amplify';

// Define a service using a base URL and expected endpoints
export const researchApi = createApi({
    reducerPath: 'researchApi',
    
    baseQuery: fetchBaseQuery({ 
        baseUrl: process.env.NEXT_PUBLIC_API_RESEARCH,
        prepareHeaders: async (headers, { getState }) => {
            const token = (await Auth.currentSession()).getIdToken().getJwtToken();
            headers.set('Authorization', `${token}`);            
            return headers;
        }
    }),
    endpoints: (builder) => ({
      getResearch: builder.query({
        query: () => `research`,
      }),
    }),
  })
  
// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetResearchQuery } = researchApi



0
投票

如果有人正在寻找更新的(2024 年第一季度)答案,这对我有用:

import...
import { fetchAuthSession } from "aws-amplify/auth";

...
prepareHeaders: async (headers) => {
      var cognitoTokens = (await fetchAuthSession()).tokens;
      let token: any = cognitoTokens?.idToken?.toString();

      if (token) {
        headers.set("Authorization", `Bearer ${token}`);
      }
      return headers;
    },
...
© www.soinside.com 2019 - 2024. All rights reserved.