Notice
Recent Posts
Recent Comments
Link
SeouliteLab
파이썬으로 구글 인증 처리하기: google-auth 모듈 활용법 본문
파이썬에서 구글 API를 사용하기 위해서는 사용자를 인증하는 과정이 필요합니다. 이를 위해 google-auth 모듈을 사용하면 구글 인증 프로세스를 간편하게 처리할 수 있습니다. 이제 몇 가지 예제를 통해 google-auth 모듈의 활용법을 알아보겠습니다.
예제 1: OAuth 2.0 인증 흐름
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# 사용자 인증 흐름 시작
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json',
scopes=['https://www.googleapis.com/auth/calendar.readonly']
)
credentials = flow.run_local_server(port=0)
# 인증된 사용자 정보 출력
print(credentials)
이 예제에서는 OAuth 2.0을 사용하여 사용자를 인증하는 흐름을 보여줍니다. 클라이언트 비밀키가 포함된 credentials.json 파일을 사용하여 사용자의 권한을 받고, 인증된 사용자 정보를 출력합니다.
예제 2: 서비스 계정으로 인증하기
from google.oauth2 import service_account
# 서비스 계정 인증 설정
credentials = service_account.Credentials.from_service_account_file(
'service-account.json',
scopes=['https://www.googleapis.com/auth/drive']
)
# 인증된 서비스 계정 정보 출력
print(credentials)
이 예제에서는 서비스 계정을 사용하여 구글 API에 인증하는 방법을 보여줍니다. service-account.json 파일을 사용하여 서비스 계정의 권한을 받고, 인증된 서비스 계정 정보를 출력합니다.
예제 3: 캐시된 인증 정보 사용하기
from google.auth import default
# 캐시된 인증 정보 가져오기
credentials, project = default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
# 캐시된 인증 정보 출력
print(credentials)
이 예제에서는 google-auth를 사용하여 캐시된 인증 정보를 가져오는 방법을 보여줍니다. 캐시된 인증 정보는 기본적으로 사용할 수 있는 권한이 포함되어 있으며, 이를 출력합니다.