>  기사  >  백엔드 개발  >  Python에서 암호 키를 통합하는 방법(FastAPI)

Python에서 암호 키를 통합하는 방법(FastAPI)

WBOY
WBOY원래의
2024-08-31 14:43:03327검색

소개

이 가이드에서는 FastAPI 프레임워크를 사용하여 암호 키 인증을 Python 웹 애플리케이션에 통합하는 과정을 안내합니다. 이 구현은 패스키 백엔드와의 통합을 간소화하는 Corbado의 passkey-first web-js 패키지를 활용합니다. 이 튜토리얼이 끝나면 패스키 기반 인증을 갖춘 FastAPI 앱이 작동하게 됩니다.

여기에서 전체 원본 튜토리얼을 읽어보세요

FastAPI 암호키 통합을 위한 전제 조건

이 튜토리얼을 따르려면 Python, FastAPI, HTML 및 JavaScript에 대한 기본적인 이해가 있어야 합니다. 
또한 암호 키 서비스를 사용하려면 Corbado 계정이 필요합니다. 시작해 보세요!

FastAPI 패스키 프로젝트 구조

FastAPI 프로젝트에는 여러 주요 파일이 포함됩니다. 필수 항목은 다음과 같습니다.

├── .env                 # Contains all environment variables
├── main.py              # Contains our webapplication (Handles routes)
└── templates
 ├── index.html       # Login page
 └── profile.html     # Profile page

Corbado 계정 설정

코딩을 시작하기 전에 Corbado 계정을 설정하세요. 그러면 해당 회사의 암호 키 서비스에 액세스할 수 있습니다. 다음 단계를 따르세요.

  1. 가입: Corbado 개발자 패널에 등록하세요.
  2. 프로젝트 만들기: 설정 중에 프로젝트 이름을 지정하고 "Corbado Complete"를 선택하세요.
  3. 환경 설정: 환경으로 "DEV"를 선택하고 애플리케이션 유형으로 "웹 앱"을 선택합니다.
  4. 세션 관리: 암호 키 인증과 세션 관리를 모두 처리하려면 "Corbado 세션 관리"를 선택하세요.
  5. 프런트엔드 프레임워크: 프론트엔드 프레임워크로 "Vanilla JS"를 선택하세요.
  6. 구성: 애플리케이션 URL(예: http://localhost:8000) 및 신뢰 당사자 ID(예: localhost)를 설정합니다.

설정 후에는 FastAPI 프로젝트에 통합할 HTML/JavaScript 스니펫을 받게 됩니다.

FastAPI 프로젝트 초기화

main.py 파일을 아직 작성하지 않았다면 작성부터 시작하세요. 다음을 사용하여 FastAPI 및 기타 필수 패키지를 설치하세요.

pip install fastapi python-dotenv passkeys

main.py는 경로 설정 및 세션 관리를 포함한 애플리케이션 로직을 처리합니다.

환경 변수 구성

프로젝트 루트에서 환경 변수를 저장할 .env 파일을 만듭니다.

PROJECT_ID=your_project_id
API_SECRET=your_api_secret

python-dotenv를 사용하여 애플리케이션에 다음 변수를 로드하세요.

from dotenv import load_dotenv
import os

load_dotenv()
PROJECT_ID = os.getenv("PROJECT_ID")
API_SECRET = os.getenv("API_SECRET")

세션 관리를 사용하여 HTML 템플릿 만들기

다음으로 HTML 템플릿을 설정하세요. template/ 디렉토리에서 login.html과 profile.html을 생성합니다. 여기에는 Corbado의 인증 구성 요소를 통합하는 데 필요한 JavaScript가 포함됩니다.
login.html의 기본 구조는 다음과 같습니다.

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://unpkg.com/@corbado/web-js@latest/dist/bundle/index.css" />
    <script src="https://unpkg.com/@corbado/web-js@latest/dist/bundle/index.js"></script>
</head>
<body>
    <script>
        (async () => {
            await Corbado.load({
                projectId: "{{ PROJECT_ID }}",
                darkMode: "off",
                setShortSessionCookie: "true",
            });
            Corbado.mountAuthUI(document.getElementById('corbado-auth'), {
                onLoggedIn: () => window.location.href = '/profile',
            });
        })();
    </script>
    <div id="corbado-auth"></div>
</body>
</html>

profile.html의 경우 사용자 데이터와 로그아웃 버튼을 표시하는 요소를 포함합니다.

<!DOCTYPE html>
<html>
  <head>
    <link
      rel="stylesheet"
      href="https://unpkg.com/@corbado/web-js@latest/dist/bundle/index.css"
      />
      <script src="https://unpkg.com/@corbado/web-js@latest/dist/bundle/index.js"></script>
    </head>
    <body>

      <!-- Define passkey-list div and logout button -->
    <h2>:/protected ?</h2>
    <p>User ID: {{USER_ID}}</p>
    <p>Name: {{USER_NAME}}</p>
    <p>Email: {{USER_EMAIL}}</p>
    <div id="passkey-list"></div>
    <button id="logoutButton">Logout</button>


    <!-- Script to load Corbado and mount PasskeyList UI -->
    <script>
 (async () => {
            await Corbado.load({
                projectId: "{{ PROJECT_ID }}",
                darkMode: "off",
                setShortSessionCookie: "true" // set short session cookie automatically
 }); 

            // Get and mount PasskeyList UI
            const passkeyListElement = document.getElementById("passkey-list"); // Element where you want to render PasskeyList UI
            Corbado.mountPasskeyListUI(passkeyListElement);

            // Get the logout button
            const logoutButton = document.getElementById('logoutButton');
            // Add event listener to logout button
 logoutButton.addEventListener('click', function() {
              Corbado.logout()
 .then(() => {
                        window.location.replace("/");
 })
 .catch(err => {
                        console.error(err);
 });
 });
 })();
    </script>


</body>
</html>

FastAPI 컨트롤러 설정

컨트롤러 로직은 main.py 파일에 있습니다. 이 파일은 로그인 페이지와 프로필 페이지 모두에 대한 경로를 관리합니다. 로그인 경로는 단순히 PROJECT_ID를 템플릿에 삽입하는 반면 프로필 경로는 Corbado의 Python SDK를 사용하여 세션을 검증하고 사용자 데이터를 가져옵니다.

main.py 예:

from typing import List
from corbado_python_sdk.entities.session_validation_result import (
    SessionValidationResult,
)
from corbado_python_sdk.generated.models.identifier import Identifier

from fastapi import FastAPI, Request, Response
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from dotenv import load_dotenv
import os
from corbado_python_sdk import (
    Config,
    CorbadoSDK,
    IdentifierInterface,
    SessionInterface,
)

load_dotenv()

app = FastAPI()

templates = Jinja2Templates(directory="templates")

PROJECT_ID: str = os.getenv("PROJECT_ID", "pro-xxx")
API_SECRET: str = os.getenv("API_SECRET", "corbado1_xxx")

# Session config
short_session_cookie_name = "cbo_short_session"

# Config has a default values for 'short_session_cookie_name' and 'BACKEND_API'
config: Config = Config(
    api_secret=API_SECRET,
    project_id=PROJECT_ID,
)

# Initialize SDK
sdk: CorbadoSDK = CorbadoSDK(config=config)
sessions: SessionInterface = sdk.sessions
identifiers: IdentifierInterface = sdk.identifiers


@app.get("/", response_class=HTMLResponse)
async def get_login(request: Request):
    return templates.TemplateResponse(
        "login.html", {"request": request, "PROJECT_ID": PROJECT_ID}
    )


@app.get("/profile", response_class=HTMLResponse)
async def get_profile(request: Request):
    # Acquire cookies with your preferred method
    token: str = request.cookies.get(config.short_session_cookie_name) or ""
    validation_result: SessionValidationResult = (
        sessions.get_and_validate_short_session_value(short_session=token)
    )
    if validation_result.authenticated:

        emailList: List[Identifier] = identifiers.list_all_emails_by_user_id(
            user_id=validation_result.user_id
            or ""  # at this point user_id should be non empty string since user was authenticated
        )

        context = {
            "request": request,
            "PROJECT_ID": PROJECT_ID,
            "USER_ID": validation_result.user_id,
            "USER_NAME": validation_result.full_name,
            "USER_EMAIL": emailList[0].value,
        }
        return templates.TemplateResponse("profile.html", context)

    else:
        return Response(
            content="You are not authenticated or have not yet confirmed your email.",
            status_code=401,
        )


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=8000)

FastAPI 애플리케이션 실행

마지막으로 FastAPI 애플리케이션을 실행하려면 Uvicorn을 설치하세요.

pip install 'uvicorn[standard]'

그런 다음 서버를 시작하세요.

uvicorn main:app --reload

UI 구성요소가 실제로 작동하는 모습을 보려면 브라우저에서 http://localhost:8000을 방문하세요.

How to Integrate Passkeys in Python (FastAPI)

결론

이 튜토리얼에서는 Corbado의 web-js 패키지를 사용하여 패스키 인증을 FastAPI 애플리케이션에 통합하는 방법을 보여주었습니다. 이 설정은 안전하고 현대적인 인증 방법을 제공하는 동시에 사용자 세션을 원활하게 관리합니다. 이 구현 확장이나 기존 앱과의 통합에 대한 자세한 내용은 Corbado 문서를 참조하세요.

위 내용은 Python에서 암호 키를 통합하는 방법(FastAPI)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:유형주조 Par-06다음 기사:유형주조 Par-06