HTTP 기본 인증이란?
[WEB] HTTP 기본 인증(Basic Authentication)
HTTP 기본 인증이란? HTTP 기본 인증은 서버가 클라이언트에게 요구하는 인증 방법 중 하나로 HTTP 헤더를 통해서 진행된다. 기본 인증 사용 이유 API 인증: RESTful API나 다른 HTTP 기반 API에서 클라이언
newbission.tistory.com
개요
Flask-HTTPAuth는 Flask에서 HTTP 기본 인증(Basic Authentication)을 다루기 위한 패키지다.
기본 인증 외에도 다이제스트(Digest) 및 토큰 인증도 지원한다.
설치 및 링크
> pip install Flask-HTTPAuth
사용 방법
from flask import Flask, render_template
from flask_httpauth import HTTPBasicAuth
app = Flask(__name__)
auth = HTTPBasicAuth()
# 사용자 정보
users = {
"admin": "secret",
"guest": "guest"
}
@auth.verify_password
def verify_password(username, password):
if username in users and users[username] == password:
return username
@app.route('/protected')
@auth.login_required
def protected():
return render_template('secret.html')
@app.route('/')
def index():
return render_template('index.html')
@auth.error_handler
def auth_error(status):
return "Access Denied", status
if __name__ == '__main__':
app.run(debug=True)
@auth.verify_password
(사용자 인증)- 사용자 이름과 비밀번호가 유효한지 확인하는 함수를 정의
- 여기서는 간단한 딕셔너리
users
를 사용하여 사용자 이름과 비밀번호를 확인 - 실전 환경에서는 데이터베이스 또는 다른 안전한 저장소를 사용
@auth.login_required
(라우트 보호)- 인증된 사용자만 해당 라우트로 접근할 수 있도록 하는 목적. 사용자 인증을 요구.
@auth.error_handler
(오류 핸들링)- 인증에 실패했을 때의 동작을 정의
- 401 코드 또는 403 상태 코드와 함께 사용할 수 있음
- 상태 코드가 제공되지 않으면 기본 오류 응답 생성
- 보안강화
HTTPS
를 사용하여 보안강화 가능- 실제 프로덕션 환경에서는 더 견고한 인증 방식인
OAuth
,JWT
방식을 사용 권장
실습용 HTML 파일
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcome to the Home Page</h1>
<a href="/protected">Go to Protected Resource</a>
</body>
</html>
<!-- templates/secret.html -->
<!DOCTYPE html>
<html>
<head>
<title>Secret Page</title>
</head>
<body>
<h1>Secret Page</h1>
<p>Welcome to the secret page!</p>
<!-- 여기에 보호된 콘텐츠나 기능을 추가할 수 있습니다. -->
<a href="/">Home</a>
<a href="/logout">Logout</a>
</body>
</html>
참고
- 오즈코딩스쿨 Flask 수업자료 | 김인섭 강사
- Flask-HTTPAuth Document
Welcome to Flask-HTTPAuth’s documentation! — Flask-HTTPAuth documentation
Welcome to Flask-HTTPAuth’s documentation! Flask-HTTPAuth is a Flask extension that simplifies the use of HTTP authentication with Flask routes. Basic authentication examples The following example application uses HTTP Basic authentication to protect rou
flask-httpauth.readthedocs.io
'Python' 카테고리의 다른 글
[Python] 주석 (1) | 2024.07.03 |
---|---|
[Flask] Flask-Login (0) | 2024.03.27 |