Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgsi/176f2cb3a9254c427b2e437f2551c706 to your computer and use it in GitHub Desktop.
Save kgsi/176f2cb3a9254c427b2e437f2551c706 to your computer and use it in GitHub Desktop.
React(React Create App)でベーシック認証とhttps正規化を行う方法メモ

React(React Create App)でベーシック認証+https正規化

前提

  • React Create Appでbasic認証を実現するためのメモ。ログイン画面や認証を作るほどでもないが、簡易で認証を付けるために設定する場合に使う
  • React Create Appでserveされた環境にbasic認証をかけるのは難しいので、buildされたアプリケーションのディレクトリにexpressのパスを設定する

想定環境

  • Node.jsが動くサーバー環境
    • Herokuとか
  • React Create Appを使う環境

必要Package

  • basic-auth
  • express

コマンド

build後にserver.jsを実行する環境を構築する。yarn startにexpressを実行するコマンドを設定。

node server/server.js

コード

auth.js

const auth = require('basic-auth')

module.exports = (request, response, next) => {
  const user = auth(request)

  if (user) {
    const usename = '設定username'
    const password = '設定password'

    if (user.name === usename && user.pass === password) {
      return next()
    }
  }

  response.set('WWW-Authenticate', 'Basic realm="example"')
  return response.status(401).send()
}

server.js

const express = require('express')
const path = require('path')
const auth = require('./auth')

const app = express()
const port = process.env.PORT || 3000
const publicPath = path.join(__dirname, '..', 'build')

app.all('*', (req, res, next) => {
  if (req.headers['x-forwarded-proto'] && req.headers['x-forwarded-proto'] !== 'https') {
    res.redirect('https://' + req.headers.host + req.url)
  } else {
    next()
  }
})

app.use(auth)
app.use(express.static(publicPath))
app.get('*', (req, res) => {
  res.sendFile(path.join(publicPath, 'index.html'))
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}!`)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment