Как получить доступ к безопасным express маршрутам приложения (Auth0) с помощью Postman? - PullRequest
0 голосов
/ 29 февраля 2020

Я последовал этому уроку: https://auth0.com/blog/manage-a-collection-of-secure-api-endpoints-with-postman/#Authorization -in-Postman

Это работает очень хорошо, и я могу получить свой токен доступа.

В моем приложении Node / Express есть маршруты, защищенные промежуточным ПО. Вход в систему осуществляется с помощью стратегии паспорта Auth0.

Когда я пытаюсь вызвать эти маршруты из Почтальона, используя маркер доступа, предоставленный в соответствии с вышеприведенным руководством, я просто получаю ответ, направляющий меня на страницу входа в Auth0. В конечном счете, мне будет сложно создать бэкэнд, если мне придется создавать внешний интерфейс только для проверки защищенных маршрутов.

Это ответ Почтальона:

<html>

<head>
    <title>Sign In with Auth0</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="robots" content="noindex, nofollow">
    <link rel="shortcut icon" href="https://cdn.auth0.com/styleguide/components/2.0.2/media/logos/img/favicon.png">
</head>

...etc

Это мой маршрут:

app.get("/test", secured, (req, res) => {
res.send("Hiya!");
});

Это промежуточное ПО (защищенное):

module.exports = (req, res, next) => {
  if (!req.user) {
    req.session.returnTo = req.originalUrl;
    return res.redirect("/auth/login");
  }
  next();
};

Это моя реализация паспорта:

const passport = require("passport");
const auth0Strategy = require("passport-auth0");
const keys = require("../config/keys");
require("../models/user");
const mongoose = require("mongoose");

const User = mongoose.model("user");

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});

// Configure Passport to use Auth0
const strategy = new auth0Strategy(
  {
    domain: keys.authDomain,
    clientID: keys.authClientID,
    clientSecret: keys.authClientSecret,
    callbackURL: keys.authCallbackURL
  },
  async (accessToken, refreshToken, extraParams, profile, done) => {
    try {
      const existingUser = await User.findOne({ authId: profile.id });
      if (existingUser) {
        return done(null, { ...existingUser, ...profile });
      }

      const user = await new User({
        authId: profile.id
      }).save();

      return done(null, profile);
    } catch (error) {
      res.send(error);
    }
  }
);

// Apply passport middleware
passport.use(strategy);
...