· 7 years ago · Feb 19, 2018, 04:48 AM
1
2
3from pyoauth.oauth1 import Credentials
4from pyoauth.oauth1.client import Client
5
6client_credentials = Credentials(
7 identifier="CONSUMER KEY",
8 shared_secret="CONSUMER SECRET"
9)
10
11oauth_client = Client(
12 client_credentials,
13 temporary_credentials_request_uri="REQUEST TOKEN URL",
14 token_credentials_request_uri="ACCESS TOKEN URL",
15 resource_owner_authorization_uri="AUTHORIZATION URL",
16 use_authorization_header=True # will use the "Authorization" HTTP header for OAuth parameters.
17)
18
19http_client = None # Use your HTTP client.
20
21class LoginHandler(RequestHandler):
22 def get(self):
23
24 # Ask the OAuth server for the "request token"
25 req = oauth_client.build_temporary_credentials_request(
26 realm="Photos",
27 oauth_callback="CALLBACK URL"
28 )
29 response = http_client.request(
30 method=req.method,
31 payload=req.payload,
32 headers=req.headers,
33 url=req.url
34 )
35
36 # Extract the request token from the OAuth server's response.
37 response = ResponseProxy(
38 response.status_code,
39 response.status,
40 response.body,
41 response.headers
42 )
43 _, request_token = client.parse_temporary_credentials_response(response)
44
45
46 # Send (redirect) the user to the authorization URL created from the request token.
47 self.redirect(client.get_authorization_url(request_token))
48
49
50# Wait for the browser to return user to your callback URL.
51# Handle the callback URL taking these query params out.
52# In your callback handler
53
54class MyCallbackHandler(RequestHandler):
55 def get(self):
56 oauth_token = self.request.get('oauth_token')
57 oauth_verifier = self.request.get('oauth_verifier')
58
59 # You need to check the verification code before you
60 # ask the server for the "access token".
61 oauth_client.check_verification_code(request_token, oauth_token, oauth_verifier)
62
63 # Now ask for the "Access token".
64 req = oauth_client.build_token_credentials_request(
65 realm="Photos",
66 request_token,
67 oauth_verifier
68 )
69 response = http_client.request(
70 method=req.method,
71 payload=req.payload,
72 headers=req.headers,
73 url=req.url
74 )
75
76 # Extract the "access token" from the response.
77 response = ResponseProxy(
78 response.status_code,
79 response.status,
80 response.body,
81 response.headers
82 )
83 _, access_token = oauth_client.parse_token_credentials_response(response)
84
85 # Save this access token to your database somewhere.
86 user.access_token = access_token
87 user.put()
88
89 # To use the access token (in this or any other handler)
90 req = oauth_client.build_resource_request(
91 access_token,
92 url="/api/username",
93 method="GET",
94 )
95 response = http_client.request(
96 method=req.method,
97 url=req.url,
98 headers=req.headers,
99 payload=req.payload
100 )
101
102 # Do what you want with the response here.
103 # ....