요청-인증

이 장에서는 요청 모듈에서 사용할 수있는 인증 유형에 대해 설명합니다.

우리는 다음을 논의 할 것입니다.

  • HTTP 요청에서 인증 작업
  • 기본 인증
  • 다이제스트 인증
  • OAuth2 인증

HTTP 요청에서 인증 작업

HTTP 인증은 클라이언트가 URL을 요청할 때 사용자 이름, 비밀번호와 같은 일부 인증 정보를 요청하는 서버 측에 있습니다. 이는 클라이언트와 서버간에 교환되는 요청 및 응답에 대한 추가 보안입니다.

클라이언트 측에서 이러한 추가 인증 정보, 즉 사용자 이름과 암호가 헤더로 전송 될 수 있으며 나중에 서버 측에서 유효성이 검사됩니다. 인증이 유효한 경우에만 서버 측에서 응답이 전달됩니다.

요청 라이브러리에는 requests.auth에서 가장 일반적으로 사용되는 인증이 있으며, 기본 인증 ( HTTPBasicAuth ) 및 다이제스트 인증 ( HTTPDigestAuth )입니다.

기본 인증

이것은 서버에 인증을 제공하는 가장 간단한 형태입니다. 기본 인증을 사용하기 위해 요청 라이브러리와 함께 사용할 수있는 HTTPBasicAuth 클래스를 사용할 것입니다.

예

다음은 사용 방법에 대한 실제 예제입니다.

import requests
from requests.auth import HTTPBasicAuth
response_data = 
requests.get('httpbin.org/basic-auth/admin/admin123', 
auth = HTTPDigestAuth('admin', 'admin123'))
print(response_data.text)

URL을 호출하고 있습니다. https://httpbin.org/basic-auth/admin/admin123사용자는 admin 이고 암호는 admin123입니다 .

따라서이 URL은 인증, 즉 사용자 및 암호 없이는 작동하지 않습니다. auth 매개 변수를 사용하여 인증을 제공하면 서버 만 응답을 반환합니다.

산출

E:\prequests>python makeRequest.py
{
   "authenticated": true,
   "user": "admin"
}

다이제스트 인증

이것은 요청에 사용할 수있는 또 다른 인증 형식입니다. 요청에서 HTTPDigestAuth 클래스를 사용할 것입니다.

예

import requests
from requests.auth import HTTPDigestAuth
response_data = 
requests.get('https://httpbin.org/digest-auth/auth/admin/admin123', 
auth = HTTPDigestAuth('admin', 'admin123'))
print(response_data.text)

산출

E:\prequests>python makeRequest.py
{
   "authenticated": true,
   "user": "admin"
}

OAuth2 인증

OAuth2 인증을 사용하려면“requests_oauth2”라이브러리가 필요합니다. "requests_oauth2"를 설치하려면 다음을 수행하십시오.

pip install requests_oauth2

설치하는 동안 터미널에 표시되는 내용은 다음과 같습니다.

E:\prequests>pip install requests_oauth2
Collecting requests_oauth2
Downloading https://files.pythonhosted.org/packages/52/dc/01c3c75e6e7341a2c7a9
71d111d7105df230ddb74b5d4e10a3dabb61750c/requests-oauth2-0.3.0.tar.gz
Requirement already satisfied: requests in c:\users\xyz\appdata\local\programs
\python\python37\lib\site-packages (from requests_oauth2) (2.22.0)
Requirement already satisfied: six in c:\users\xyz\appdata\local\programs\pyth
on\python37\lib\site-packages (from requests_oauth2) (1.12.0)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\use
rs\xyz\appdata\local\programs\python\python37\lib\site-packages (from requests
->requests_oauth2) (1.25.3)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\xyz\appdata\loca
l\programs\python\python37\lib\site-packages (from requests->requests_oauth2) (2
019.3.9)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\users\xyz\appdata\l
ocal\programs\python\python37\lib\site-packages (from requests->requests_oauth2)
(3.0.4)
Requirement already satisfied: idna<2.9,>=2.5 in c:\users\xyz\appdata\local\pr
ograms\python\python37\lib\site-packages (from requests->requests_oauth2) (2.8)
Building wheels for collected packages: requests-oauth2
Building wheel for requests-oauth2 (setup.py) ... done
Stored in directory: C:\Users\xyz\AppData\Local\pip\Cache\wheels\90\ef\b4\43
3743cbbc488463491da7df510d41c4e5aa28213caeedd586
Successfully built requests-oauth2

"requests-oauth2"설치가 완료되었습니다. Google, Twitter의 API를 사용하려면 동의가 필요하며 OAuth2 인증을 사용하여 동일하게 수행됩니다.

OAuth2 인증을 위해서는 클라이언트 ID와 비밀 키가 필요합니다. 그것을 얻는 방법에 대한 자세한 내용은https://developers.google.com/identity/protocols/OAuth2.

나중에 사용할 수있는 Google API 콘솔에 로그인합니다. https://console.developers.google.com/클라이언트 ID와 비밀 키를 가져옵니다.

예

다음은 "requests-oauth2"를 사용하는 방법의 예입니다.

import requests
from requests_oauth2.services import GoogleClient
google_auth = GoogleClient(
   client_id="xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
   redirect_uri="http://localhost/auth/success.html",
)
a = google_auth.authorize_url(
   scope=["profile", "email"],
   response_type="code",
)
res = requests.get(a)
print(res.url)

Gmail 계정에 로그인해야하므로 제공된 URL로 리디렉션 할 수 없지만 여기에서는 google_auth가 작동하고 승인 된 URL이 제공된 예를 볼 수 있습니다.

산출

E:\prequests>python oauthRequest.py
https://accounts.google.com/o/oauth2/auth?redirect_uri=
http%3A%2F%2Flocalhost%2Fauth%2Fsuccess.html&
client_id=xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com&
scope=profile+email&response_type=code