繁体   English   中英

Next.JS登录后如何调用auth0 api?

[英]How to call auth0 api after log in in Next.JS?

我有一个 Next.JS 应用程序,我在其中使用文档中的代码实现了 auth0 登录:

// pages/api/auth/[...auth0].js
import { handleAuth } from '@auth0/nextjs-auth0';

export default handleAuth();
// pages/index.js
import { useUser } from '@auth0/nextjs-auth0';

export default function Profile() {
  const { user, error, isLoading } = useUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;

  return (
    user && (
      <div>
        <img src={user.picture} alt={user.name} />
        <h2>{user.name}</h2>
        <p>{user.email}</p>
      </div>
    )
  );
}

该代码正在运行,我可以登录。 当我理解正确时,我的 index.js 现在受到保护。

然后我在auth0里面加了一个API的应用。

现在我在 node.js 中创建了一个小服务器:

const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const helmet = require("helmet");
const jwt = require("express-jwt");
const jwks = require("jwks-rsa");
const authConfig = require("./auth_config.json");

const app = express();

const port = process.env.API_PORT || 3001;
const appPort = process.env.SERVER_PORT || 3000;
const appOrigin = authConfig.appOrigin || `http://localhost:${appPort}`;

if (!authConfig.domain || !authConfig.audience) {
  throw new Error(
    "Please make sure that auth__config.json is in place and poplated"
  );
}

const jwtCheck = jwt({
  secret: jwks.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://${authConfig.domain}/.well-known/jwks.json`,
  }),
  audience: authConfig.audience,
  issuer: `http://${authConfig.domain}`,
  algorithms: ["RS256"],
});

app.use(morgan("dev"));
app.use(helmet());
app.use(cors({ origin: appOrigin }));
app.use(jwtCheck);

app.get("/api/protected", (reg, res) => {
  res.send({
    msg: "You called the protected endpoint!",
  });
});

app.listen(port, () => console.log(`API server listening on port ${port}`));

我现在的问题是:如何从 index.js 调用api/protected路径?

如果我理解正确,您是在问如何在您的组件内进行 api 调用? 如果是,下面是一个例子。

import axios from "axios";

const yourfunctionName = async (email, password) => {
  try {
      const response = await axios.get(`http://localhost:3000/api/protected`, {
        data
      });
      return response.data
    } catch (error) {
        console.log(error.message);
      } 
};

看一下示例useFetchUser hook

此处仅在用户登录时才发送对/api/me端点的 HTTP 调用。

在示例主页中,通过调用 hook加载用户:

const { user, loading } = useFetchUser()

你会做类似的事情,但它会略有不同,因为你不需要在useProtectedInfo或任何你决定调用你的钩子的主体中进行有条件的重定向。

该结构将与示例大体相似。

我这样做的方式如下。

  1. 通过在pages/api/myendpoint.ts中创建一个文件,向您的服务器添加一个 API 调用
import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0';
import axios, { AxiosRequestConfig } from 'axios';

export default withApiAuthRequired(async function myendpoint(req, res) {
  try {
    const { accessToken } = await getAccessToken(req, res, {
      scopes: []
    });

    const baseURL = 'http://localhost:3000';

    const config: AxiosRequestConfig = {
      headers: { Authorization: `Bearer ${accessToken}` }
    };
    const response = await axios.post(baseURL + '/api/protected', {
        'someThing': req.query.someThing,
        'comment': 'string'
      }, config
    );

   
    res.status(response.status || 200).json(response.data);
  } catch (error: any) {
    console.error(error);
    res.status(error.status || 500).json({
      code: error.code,
      error: error.message
    });
  }
});
  1. 从您的前端调用 API 方法
export default function Article(params: { blog: any, id: string }) {
const handleSubmit = async (event: any) => {
    event.preventDefault();

    // Get data from the form.
    const postData = {
      comment: event.target.comment.value,
      page: event.target.page.value
    };

    // Send the data to the server in JSON format.
    const JSONdata = JSON.stringify(postData);

    // API endpoint where we send form data.
    const endpoint = '/api/myendpoint';

    // Form the request for sending data to the server.
    const options = {
      // The method is POST because we are sending data.
      method: 'POST',
      // Tell the server we're sending JSON.
      headers: {
        'Content-Type': 'application/json'
      },
      // Body of the request is the JSON data we created above.
      body: JSONdata
    };

    // Send the form data to our forms API on Vercel and get a response.
    const response = await fetch(endpoint, options);

    // Get the response data from server as JSON.
    // If server returns the name submitted, that means the form works.
    const result = await response.json();

    // do something with result
  };

  return (<form onSubmit={handleSubmit}>
    <input type='hidden' name='key' value={someValue} />
    <textarea name='someThing' className='px-3 py-2 border text-sm h-16 pt-2 pr-3 pb-2 pl-3 w-full text-gray-700 dark:text-white border-gray-300 rounded-md
                            placeholder-gray-600 dark:placeholder-gray-200 focus:shadow-outline'
              placeholder='Enter some text' required></textarea>
    <button type='submit'
            className='inline-flex w-full justify-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-base font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 sm:text-sm'>Submit
    </button>
  </form>);

调用内部 API 方法来进行外部 API 调用似乎有点多余,但我只能找到遵循此设计的示例。 如果有更好的方法,很高兴得到纠正!

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM