Python용 MSAL(Microsoft 인증 라이브러리)

Python용 Microsoft 인증 라이브러리를 시작하여 Microsoft ID(Azure AD, Microsoft 계정Azure ADB2C 계정)를 사용하여 사용자 또는 앱에 로그인하고 Microsoft Graph와 같은 Microsoft API 또는 Microsoft ID 플랫폼 등록된 사용자 고유의 API를 호출하는 토큰을 가져옵니다.

단계에 따라 패키지를 설치하고 기본 작업을 위한 예제 코드를 사용해 봅니다.

퀵 스타트 | API 참조 설명서 | 샘플

필수 구성 요소

패키지 설치

Python용 MSAL 패키지를 설치합니다. Pypi에서 MSAL Python을 찾을 수 있습니다.

pip install msal

설치

MSAL Python을 사용하기 전에 애플리케이션을 Microsoft ID 플랫폼 등록합니다.

사용

MSAL Python을 사용하여 토큰을 획득하는 것은 이 3단계 패턴을 따릅니다. 이것은 높은 수준의 개념적 패턴입니다. 다른 흐름에 대한 몇 가지 변형이 있습니다. 실행 가능한 샘플에서 설명합니다.

  1. MSAL은 퍼블릭 클라이언트 애플리케이션과 기밀 클라이언트 애플리케이션 간의 깨끗한 분리를 제안합니다. 따라서 또는 인스턴스를 PublicClientApplicationConfidentialClientApplication 만들고 앱의 수명 주기 동안 다시 사용합니다. 다음 예제에서는 를 보여줍니다.PublicClientApplication

    from msal import PublicClientApplication
    app = PublicClientApplication(
        "your_client_id",
        authority="https://login.microsoftonline.com/Enter_the_Tenant_Name_Here")
    

    나중에 액세스 토큰을 원할 때마다 다음을 시작합니다.

    result = None  # It is just an initial value. Please follow instructions below.
    
  2. MSAL의 API 모델은 토큰 캐시를 활용하는 방법에 대한 명시적 제어를 제공합니다. 이 캐시 부분은 기술적으로 선택 사항이지만 MSAL 캐시의 성능을 활용하는 것이 좋습니다. 자동으로 토큰 새로 고침을 처리합니다.

    # We now check the cache to see
    # whether we already have some accounts that the end user already used to sign in before.
    accounts = app.get_accounts()
    if accounts:
        # If so, you could then somehow display these accounts and let end user choose
        print("Pick the account you want to use to proceed:")
        for a in accounts:
            print(a["username"])
        # Assuming the end user chose this one
        chosen = accounts[0]
        # Now let's try to find a token in cache for this account
        result = app.acquire_token_silent(["your_scope"], account=chosen)
    
  3. 캐시에 적합한 토큰이 없거나 이전 단계를 건너뛰도록 선택한 경우 토큰을 가져오기 위해 Azure AD 요청을 보냅니다. 클라이언트 유형 및 시나리오에 따라 다른 방법이 있습니다. 여기서는 자리 표시자 흐름을 보여 줍니다.

    if not result:
        # So no suitable token exists in cache. Let's get a new one from Azure AD.
        result = app.acquire_token_by_one_of_the_actual_method(..., scopes=["User.Read"])
    if "access_token" in result:
        print(result["access_token"])  # Yay!
    else:
        print(result.get("error"))
        print(result.get("error_description"))
        print(result.get("correlation_id"))  # You may need this when reporting a bug
    

MSAL Python 기능 및 사용에 대한 자세한 내용은 GitHub의 Wiki 를 참조하세요.

ADAL에서 MSAL로 마이그레이션

애플리케이션이 ADAL Python을 사용하는 경우 MSAL Python을 사용하도록 업데이트하는 것이 좋습니다. ADAL Python에서는 새로운 기능 작업이 수행되지 않습니다.

ADAL에서 MSAL로 마이그레이션 가이드를 참조하세요.

다음 단계