Ошибка порта при развертывании экспресс-сервера с OIDC в ​​службу приложений Azure

Я пытаюсь развернуть сервер в службе приложений Azure. Код сервера можно найти ниже.

Ошибка, которую я получаю из потока журнала:

2020-11-18T23: 36: 06.088Z ОШИБКА - Контейнер [имя контейнера] не ответил на запросы HTTP на порт: 8080, не удалось запустить сайт. См. Журналы контейнера для отладки.

У меня PORT установлен на 8080, и я знаю, что конфигурация набирает обороты, поскольку я вижу, что сервер прослушивает порт 8080 в журналах. Я попытался изменить WEBSITES_PORT на 80 и 8080, поскольку видел другие сообщения, но я думаю, что моя проблема в другом.

Этот сайт работал до того, как я добавил аутентификацию с библиотеками OIDC.

Приложение работает локально с серверным кодом, приведенным ниже.

const https = require('https')

const express = require('express')
const path = require('path')
const app = express()
const fs = require('fs')

const key = fs.readFileSync('./key.pem')
const cert = fs.readFileSync('./cert.pem')

require('dotenv').config()
app.use(express.json())
app.use(express.urlencoded({
  extended: true
}))
app.use(express.static('express'))
var cors = require('cors')
const OktaJwtVerifier = require('@okta/jwt-verifier')
const session = require('express-session')
const {
  ExpressOIDC
} = require('@okta/oidc-middleware')

var getUserInfo = require('./getUserInfo')

// session support is required to use ExpressOIDC
app.use(
  session({
    secret: 'this should be secure',
    resave: true,
    saveUninitialized: false,
    cookie: {
      httpOnly: false,
      secure: true,
    },
  })
)

const oidc = new ExpressOIDC({
  issuer: process.env.ISSUER || 'https://[custom auth server domain].gov/oauth2/default',
  client_id: process.env.CLIENT_ID || 'xxxxxxxxxxxxxxxxx',
  client_secret: process.env.CLIENT_SECRET || 'xxxxxxxxxxxxxxxxxx',
  redirect_uri: process.env.REDIRECT_URI ||
    'https://localhost:3000/authorization-code/callback',
  appBaseUrl: process.env.APP_BASE_URL || 'https://localhost:3000',
  scope: 'openid profile',
})

// ExpressOIDC attaches handlers for the /login and /authorization-code/callback routes
app.use(oidc.router)

app.use(cors())
app.options('*', cors())
app.get('/userinfo', (req, res) => {
  let domain = 'dev'

  if (req.isAuthenticated()) {
    getUserInfo.userRequest(res, req.userContext, domain)
  }
})

app.get('/authStatus', (req, res) => {
  if (req.isAuthenticated()) {
    res.send(req.userContext.userinfo)
  }
})

app.post('/forces-logout', oidc.forceLogoutAndRevoke(), (req, res) => {
  // Nothing here will execute, after the redirects the user will end up wherever the `routes.logoutCallback.path` specifies (default `/`)
})

var linkObj = {not relevant links used hrefs on html based on env}

// default URL for website
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname + '/express/index.html'))
  //__dirname : It will resolve to your project folder.
})

// FAQ Path
app.get('/help', function(req, res) {
  res.sendFile(path.join(__dirname + '/express/help.html'))
  //__dirname : It will resolve to your project folder.
})

app.get('/links', (req, res) => {
  res.json(linkObj)
})

app.post('/forces-logout', oidc.forceLogoutAndRevoke(), (req, res) => {
  // Nothing here will execute, after the redirects the user will end up wherever the `routes.logoutCallback.path` specifies (default `/`)
})

// default URL for website
app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname + '/express/index.html'))
  //__dirname : It will resolve to your project folder.
})

const port = normalizePort(process.env.PORT || '3000')
if (process.env.PORT) {
  const server = https.createServer(app)
  server.listen(port)
} else {
  const server = https.createServer({
    key: key,
    cert: cert
  }, app)
  server.listen(port)
}

console.debug('Server listening on port ' + port)

function normalizePort(val) {
  var port = parseInt(val, 10)

  if (isNaN(port)) {
    // named pipe
    return val
  }

  if (port >= 0) {
    // port number
    return port
  }

  return false
}


person Jake Durell    schedule 18.11.2020    source источник


Ответы (1)


Я считаю, что эта строка может вызывать у вас проблемы:

const port = normalizePort(process.env.PORT || '3000')

Я бы попробовал изменить его на:

const port = normalizePort(process.env.PORT || '8080')

Вам также необходимо изменить эти строки, чтобы они содержали ваш общедоступный URL, а не localhost:

  redirect_uri: process.env.REDIRECT_URI ||
    'https://localhost:3000/authorization-code/callback',
  appBaseUrl: process.env.APP_BASE_URL || 'https://localhost:3000',

После того, как вы измените их, вам нужно будет обновить свое приложение на Okta до вашего производственного URI перенаправления.

person Matt Raible    schedule 19.11.2020
comment
Спасибо, Мэтт. Переменные process.env используются только при развертывании в Azure. Переменные справа от || только для местных. У меня есть конфигурация OIDC, настроенная в Okta для локального использования, а другая - для среды разработки, где у меня возникают проблемы с развертыванием. - person Jake Durell; 19.11.2020