개요
- Gihub Pages 이용을 계획해 배포를 진행했고 인증이 허가된 사용자만 접근하길 원함
- Gihub Pages에서 제공하는 Environment secrets 또는 variables를 활용해 간단한 인증 절차를 만들고자 계획
- 런타임에 인증 정보를 입력해서 접근을 허용하려 했으나, Github Pages 자체는 런타임에서 환경변수를 읽어줄 서버가 없다고 함
- 이러한 문제를 해결하기 위해 Cloudflare Pages를 대안으로 찾아 배포 진행
- 인증을 처리해줄 Middleware를 생성해서 인증에 성공한 유저만 접근 허용
내용
#1 Github Pages는 “모두”에게 공개되는 배포 사이트
- Github Pages를 통해서 손쉽게 정적 페이지를 배포할 수 있었음
gh-pages를 라이브러리를 사용하면 간단한 빌드 스크립트를 설정해서 github push 부터 deploy까지 진행 가능하기 때문- 문제는 배포되는 URL만 알고 있다면 누구든 접근이 가능한 점이 내심 불편함
- Github를 잠시 둘러봤을 때
Environment secrets와variables를 확인할 수 있었고, 설정한env값을 런타임에 가져오면 간단한 인증 절차를 만들 수 있겠다 생각함 - 그러나 Github Pages 자체는 런타임에서 환경변수를 읽어줄 서버가 없다는 것을 알아서 적용할 수 없었음
- 더군다나
secrets는 Github Actions가 실행될 때만 읽히며, (런타임 ❌) variables는 Vite가 빌드 타임에 js로 치환하고 브라우저에게 그대로 내려주므로 자연스럽게 노출되는 문제가 있었음
#2 CloudFlare Pages는 인증 절차도 코딩할 수 있는 배포 사이트
- CloudFlare Pages를 활용하면 내가 원하는 인증 절차를 적용할 수 있는 방법을 찾아냄
- 방법은 Pages Functions Middleware로 웹 애플리케이션이 서비스 되기 전에 ‘특정 코드’를 실행시키는 것
- ‘특정 코드’가 바로 내가 원하는 인증 로직
#1 USER / PASSWORD 입력
#2 환경 변수에 설정된 값과 입력된 USER / PASSWORD를 대조
#3 일치하면, 웹 애플리케이션 서비스
#4 일치하지 않으면, 허가되지 않은 유저로 안내
#3 Pages Fuctions Middleware로 인증 절차 만들기
- 간단한 절차부터 소개하면 다음과 같음
- project root 경로에
functions디렉터리 생성 - functions 디렉터리에 Authentication Middleware 생성
- 웹 애플리케이션을 CloudFlare Pages로 배포
- project root 경로에
[ 1. functions 디렉터리 생성 ]
- 다음과 같은 경로에 functions 디렉터리를 생성
my-react-app/
├── src/
├── public/
├── functions/ --> middleware 생성할 위치
└── package.json
[ 2. Authentication Middleware 생성 ]
functions디렉터리에_middleware.js파일명으로 소스파일 생성
export async function onRequest(context) {
// 요청에서 authentication header를 가져옴
const auth = context.request.headers.get('Authorization');
// 만약 authentication header가 확인되지 않으면, 인증 오류 안내
if (!auth) {
return new Response('Authentication required', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="Secure Area"' },
});
}
// authentication header에서 scheme과 encoded를 추출
const [scheme, encoded] = auth.split(' ');
// 기본 인증(Basic)을 사용하고 있는지 확인
if (scheme !== 'Basic' || !encoded) {
return new Response('Invalid authentication', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="Secure Area"' },
});
}
// 기본 인증까지 확인되면, Base64로 디코드
const decoded = atob(encoded);
// 입력된 username과 password를 분리
const [username, password] = decoded.split(':');
// 대조할 인증 정보 획득
const VALID_USERNAME = context.env.YOUR_NAME;
const VALID_PASSWORD = context.env.YOUR_PASSWORD;
// 대조 및 인증 미확인 시, 인증 오류 안내
if (username !== VALID_USERNAME || password !== VALID_PASSWORD) {
return new Response('Invalid credentials', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="Secure Area"' },
});
}
// 인증 확인까지 마치면 웹 애플리케이션 서비스 시작
return context.next();
}
[ 3. 웹 애플리케이션을 CloudFlare Pages로 배포 ]
- CloudFlare Pages로 이미 배포하고 있다면, 간단한 설정을 통해 위의 소스파일을 Github에 push
- CloudFlare Pages가 바라보는 Github repository의 branch에 commit이 발생하면 자동으로 빌드부터 배포까지 진행됨
- CloudFlare Pages 배포가 필요하다면, 다음의 글 참고
- [추가예정]
#4 환경 변수 세팅
- Compute (Workers) > Workers & Pages > [ YOUR_APPLICATION ] > Setting tab에 환경 변수 세팅
#5 실제 동작
- 웹 애플리케이션 배포를 완료하면 CloudFlare Pages가 제공해 주는 도메인으로 접속 가능
- 웹 접속하면 Middleware가 동작해 사용자 이름과 비밀번호를 요구하는 알림창이 Alert
- 인증 성공 시, 웹 애플리케이션 서비스
- 인증 실패 시, 인증이 필요하다는 안내 출력
참고
https://docs.github.com/ko/pages/getting-started-with-github-pages/creating-a-github-pages-site?
GitHub Pages 사이트 만들기 - GitHub 문서
새 리포지토리 또는 기존 리포지토리에서 GitHub Pages 사이트를 만들 수 있습니다.
docs.github.com
https://docs.github.com/en/actions/concepts/security/secrets?utm_source=chatgpt.com
Secrets - GitHub Docs
Secrets allow you to store sensitive information in your organization, repository, or repository environments. Secrets are variables that you create to use in GitHub Actions workflows in an organization, repository, or repository environment. GitHub Action
docs.github.com
https://v2.vitejs.dev/guide/env-and-mode.html?utm_source=chatgpt.com
Env Variables and Modes | Vite
Env Variables and Modes Env Variables Vite exposes env variables on the special import.meta.env object. Some built-in variables are available in all cases: import.meta.env.MODE: {string} the mode the app is running in.import.meta.env.BASE_URL: {string} the
v2.vitejs.dev
https://developers.cloudflare.com/workers/examples/basic-auth/
HTTP Basic Authentication
Shows how to restrict access using the HTTP Basic schema.
developers.cloudflare.com
https://github.com/garrison/cloudflare-pages-shared-password?tab=readme-ov-file
GitHub - garrison/cloudflare-pages-shared-password: Demonstration of a static site hosted on Cloudflare Pages with HTTP basic au
Demonstration of a static site hosted on Cloudflare Pages with HTTP basic authentication - garrison/cloudflare-pages-shared-password
github.com
Simple HTTP Basic Authentication for Cloudflare Pages
Adding authentication to your pages deployment requires a programmatic approach.
htdocs.dev
'사이드 프로젝트 아카이빙' 카테고리의 다른 글
| [HTTPS] Vite HTTPS 개발 환경용 OpenSSL 인증서 발급 가이드 (0) | 2025.11.23 |
|---|---|
| [HTTPS] Vite 개발 환경에서 HTTPS 적용하기 with Proxy (0) | 2025.11.23 |
| [Image Upload]이미지 리사이징(Resizing) with pica lib (0) | 2025.11.23 |
| [키워드 알림] 통신 방식 비교 (Polling, SSE) (1) | 2025.11.23 |
| [HTTP method] DELETE method 의견 및 사용 (0) | 2025.11.23 |