简体   繁体   English

如何从 React Native 应用程序使用 Amplify 保护的 Next.JS Rest 端点

[英]How to consume Next.JS Rest Endpoints secured with Amplify from a React Native app

Background:背景:

My current stack is a Next server to use as an admin portal and REST API for a Mobile App running with Expo - React Native.我当前的堆栈是用作管理门户的 Next 服务器,REST API 用于运行 Expo - React Native 的移动应用程序。 The Next Server is currently hosted as a Lambda@Edge. Next Server 当前托管为 Lambda@Edge。

I have secured both the Next server and the React Native app with AWS Amplify's withAuthenticator wrapper.我已使用 AWS Amplify 的 withAuthenticator 包装器保护 Next 服务器和 React Native 应用程序。 (I also tried specific auth packages like Next-Auth and Expo's auth package) (我还尝试了特定的授权包,如 Next-Auth 和 Expo 的授权包)

Problem:问题:

However, I can't figure out how to add the Auth info (Access_token) to my REST Requests from Mobile app -> Next Server但是,我无法弄清楚如何将身份验证信息(Access_token)添加到我的 REST 来自移动应用程序的请求 -> 下一个服务器

I tried adding the tokens as bearer headers to the API without luck after that I was fairly sure it all has to be set up and sent via cookies. BUT I am stuck on how to actually implement these cookies properly.我尝试将令牌作为不记名标头添加到 API 中,但没有成功,之后我相当确定所有这些都必须通过 cookies 进行设置和发送。但我仍然坚持如何正确地实际实现这些 cookies。 I was hoping the endpoints:[] config could be used to set up my own domain to post to and handle the cookies. Reading the request on the server showed that it contained no Auth info when posted with this method.我希望端点:[] 配置可用于设置我自己的域以发布和处理 cookies。读取服务器上的请求显示使用此方法发布时它不包含身份验证信息。

Likewise using RTK Query (Preferably I add all the Auth to this instead of Amplify's API setup) I don't have the correct info to make an Authorized api request同样使用 RTK 查询(最好我将所有 Auth 添加到此而不是 Amplify 的 API 设置)我没有正确的信息来发出授权的 api 请求

Here are some snippets of the working page Authentication for both apps以下是两个应用程序的工作页面身份验证的一些片段

API Endpoint /api/version: API 端点/api/版本:

import type { NextApiRequest, NextApiResponse } from 'next'
import { withSSRContext } from 'aws-amplify'

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse<Data | Error>,
) {
    const { Auth } = withSSRContext({req})

    try {
        const user = await Auth.currentAuthenticatedUser()
        return res.status(200).json({
            version: '1.0.0',
            user: user.username,
        })
    } catch (err) {
        console.log(err)
        return res.status(200).json({
            message: 'Unauthenticated',
        })
    }
}

Mobile App Config:移动应用配置:

import {
    useAuthenticator,
    withAuthenticator,
} from '@aws-amplify/ui-react-native'
import { Amplify, Auth } from 'aws-amplify'
import awsconfig from './aws-exports'

Amplify.configure({
    ...awsconfig,
    API: {
        endpoints: [
            {
                name: 'MyApi',
                endpoint: 'http://NextIP:NextPort/api/',
            },
        ],
    },
})

Auth.configure(awsconfig)

export default withAuthenticator(App)

Mobile Screen:手机屏幕:

import { API } from 'aws-amplify'

function getData() {
    const apiName = 'MyApi'
    const path = '/version'
    const myInit = {
        headers: {}, // OPTIONAL
    }

    return API.get(apiName, path, myInit)
}

export default function ModalScreen() {
    // Get token / Cookie for auth

    // const { data, isLoading, error } = useGetApiVersionQuery(null) // RTK Query
    getData() // Amplify
        .then(response => {
            console.log(response)
        })
        .catch(error => {
            console.log(error.response)
        })
    return ( <></>)}

I found a solution, however, could not get the Next-Auth middleware to fire when the token was sent using the Bearer token in headers.但是,我找到了一个解决方案,当使用标头中的 Bearer 令牌发送令牌时,无法触发 Next-Auth 中间件。 Which is my ideal way of handling the routes.这是我处理路线的理想方式。

I wrapped the getToken({req}) call so that if there is no JWT Web token it would try encode the token separately Lastly ChatGpt somehow got me onto the package aws-jwt-verify which has everything you need to verify a token generated by aws-amplify/auth, in my case from react-native.我包装了 getToken({req}) 调用,这样如果没有 JWT Web 令牌,它会尝试单独编码令牌 最后,ChatGpt 以某种方式让我进入 package aws-jwt-verify,它拥有验证由生成的令牌所需的一切aws-amplify/auth,在我的例子中来自 react-native。

components/utils/auth.utils.ts组件/utils/auth.utils.ts

import { NextApiRequest } from 'next'
import { CognitoJwtVerifier } from 'aws-jwt-verify'
import { getToken } from 'next-auth/jwt'

// Verifier that expects valid token:
const verifier = CognitoJwtVerifier.create({
    userPoolId: process.env.COGNITO_USERPOOL_ID ?? '',
    tokenUse: 'id',
    clientId: process.env.COGNITO_CLIENT_ID ?? '',
    issuer: process.env.COGNITO_ISSUER ?? '',
})

export async function getMobileToken(req: NextApiRequest) {
    let token = null
    try {
        token = await getToken({ req })
    } catch (error) {
        console.log('Could not get JWT Web Token')
    }
    try {
        if (!token)
            token = await getToken({
                req,
                async decode({ token }) {
                    if (!token) return null
                    const decoded = await verifier.verify(token)
                    return decoded
                },
            })
    } catch (error) {
        return null
    }
    console.log('Mobile Token:', token)
    return token
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Amplify中部署Next.js? - How to deploy Next.js in Amplify? 放大重定向不适用于 Next.js 应用程序中的 fonts - Amplify redirects not working for fonts in Next.js app 如何使用 AWS Amplify 和 Next.js 制作生产环境变量 - How to make production environmental variables with AWS Amplify and Next.js 使用 Next.js SSR 扩充 CDK - Amplify CDK with Next.js SSR 在 AWS Amplify 上部署 Next.js 时出错 - Error on deploying Next.js on AWS Amplify 如何在 amplify 上检查我的 next.js 服务器错误日志? - How can I check my next.js server errors logs on amplify? AWS Amplify、Next.js 和经过身份验证的 SSR 的问题 - Problems with AWS Amplify, Next.js and authenticated SSR 在 AWS Amplify 上成功部署 8825558328788 应用程序后,https://www.example.com/api/any-route 在控制台中显示以下错误 - After successfully deploying Next.js app on AWS Amplify, https://www.example.com/api/any-route showing below error in console 使用 Next.js getStaticProps 重新验证时出现 AWS Amplify 503 错误 - AWS Amplify 503 error when using Next.js getStaticProps revalidate 在 AWS Amplify 上将 Next.js 与 SSR 结合使用,环境变量不会被传递到自动创建的 Lambda - Using Next.js with SSR on AWS Amplify, Environment Variables NOT being carried through to auto-created Lambda
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM