Узел с Fusionauth passport-oauth OAuth2Strategy Ошибка: не удалось получить токен доступа - PullRequest
0 голосов
/ 24 апреля 2020

Я пытаюсь авторизовать мое приложение узла через fusionauth с паспортом и express, и я получаю ошибку узла от обратного вызова fusionauth «Не удалось получить токен доступа» после входа в fusionauth. Я не уверен, почему ответ fusionauth не включает токен?

fusionauth, ссылка для авторизации с обратным вызовом fusion_auth_server: 9011 / oauth2 / authorize? Response_type = code & redirect_uri = http% 3A% 2F % 2Flocalhost% 3A3000% 2Foauth2% 2Fcallback & client_id = 42a5 #### - #### - #### - #### - ########

 name: 'InternalOAuthError',
  message: 'Failed to obtain access token',
  oauthError:
   { Error: connect EHOSTUNREACH 0.0.35.51:80 - Local (192.168.1.46:62475)
       at internalConnect (net.js:872:16)
       at defaultTriggerAsyncIdScope (internal/async_hooks.js:294:19)
       at GetAddrInfoReqWrap.emitLookup [as callback] (net.js:1019:9)
       at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:61:10)
     errno: 'EHOSTUNREACH',
     code: 'EHOSTUNREACH',
     syscall: 'connect',
     address: '0.0.35.51',
     port: 80 } }

```
app.get('/oauth2/authorize', oauth2.authorize);
app.get('/oauth2/callback', oauth2.callback);
app.get('/oauth2/logout', oauth2.logout);

```

```
const passport = require('passport');
const OAuth2Strategy = require('passport-oauth').OAuth2Strategy;
const http = require('http');
const config = {
    "apiKey": "63353861-####-####-####-##########",
    "callbackURL": "http://localhost:3000/oauth2/callback",
    "clientID": "42a5bc23-####-####-####-#####",
    "clientSecret": "WI2Y04lkozWonBeRz_####################",
    "host": "fusion_auth_server", 
    "port": "9011"
    };

passport.use(
  'fusionauth',
  new OAuth2Strategy(
    {
      authorizationURL: `${config.host}:${config.port}/oauth2/authorize`,
      tokenURL: `${config.host}:${config.port}/oauth2/token`,
      clientID: config.clientID,
      clientSecret: config.clientSecret,
      callbackURL: config.callbackURL
    },
    function(accessToken, refreshToken, profile, done) {
      // verify accessToken was provided`enter code here`
      if (!accessToken) {
        done(null, false);
      }

      // verify token and get user info
      const options = {
        host: config.host,
        port: config.port,
        path: '/oauth2/userinfo',
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${accessToken}`
        }
      };
      const userInfoRequest = http.get(options, res => {
        var chunks = '';
        res.on('data', data => {
          chunks += data;
        });
        res.on('end', () => {
          if (res.statusCode === 200) {
            const result = JSON.parse(chunks);
            const user = {
              ...result,
              accessToken
            };

            // todo: persist user

            done(null, user);
          } else {
            done(null, false);
          }
        });
      });
      userInfoRequest.end();
    }
  )
);

const callback = (req, res, next) => {
    //console.log("callback",res)
  passport.authenticate('fusionauth', (err, user) => {
     console.log("Authenticating",err)
    if (err) {
      return next(err);
    }
    if (!user) {
      return res.redirect('http://localhost:4200/login');
    }
   // console.log(user);
    res.cookie('accessToken', user.accessToken, { httpOnly: true });
    res.redirect('http://localhost:4200');
  })(req, res, next);
};

module.exports = {

  authorize: passport.authenticate('fusionauth', {
    session: false
  }),
  callback,
  logout: (req, res) => {
    req.logout();
    res.redirect('http://localhost:4200/');
  }
};


```

Ответы [ 2 ]

1 голос
/ 24 апреля 2020

Похоже на токен http: // перед ним для разрешения на правильный IP-адрес

Изменена следующая строка: From:

tokenURL: `${config.host}:${config.port}/oauth2/token`,

To :

tokenURL: `http://${config.host}:${config.port}/oauth2/token`,
0 голосов
/ 24 апреля 2020

Похоже, какая-то сетевая ошибка, была бы моей первой догадкой. Error: connect EHOSTUNREACH 0.0.35.51:80. Это странный IP-адрес.

Я вижу, что хост конфигурации - fusion_auth_server. Это разрешает этот IP-адрес?

...