Debian Codegraph @

docs/examples/three_legged_oauth.rst

raw
1 .. _examples_three_legged_oauth_login:
2
3 Three Legged OAuth with Flask
4 -----------------------------
5
6 This type of authorization is used for web login with a server-side
7 application. For example, a Django app or other application server handles
8 requests.
9
10 This example uses Flask, but should be easily portable to other application
11 frameworks.
12
13
14 Components
15 ~~~~~~~~~~
16
17 There are two components to this application: login and logout.
18
19 Login sends a user to Globus Auth to get credentials, and then may act on the
20 user's behalf.
21 Logout invalidates server-side credentials, so that the application may no
22 longer take actions for the user, and the client-side session,
23 allowing for a fresh login if desired.
24
25 Register an App
26 ~~~~~~~~~~~~~~~
27
28 In order to complete an OAuth2 flow to get tokens, you must have a client
29 definition registered with Globus Auth.
30 To do so, follow the relevant documentation for the
31 `Globus Auth Service <https://docs.globus.org/api/auth/>`_ or go directly to
32 `developers.globus.org <https://developers.globus.org/>`_ to do the
33 registration.
34
35 Make sure that the "Native App" checkbox is unchecked, and list
36 ``http://localhost:5000/login`` in the "Redirect URIs".
37
38 On the projects page, expand the client description and click "Generate
39 Secret".
40 Save the resulting secret a file named ``example_app.conf``, along with the client ID:
41
42 .. code-block:: python
43
44 SERVER_NAME = "localhost:5000"
45 # this is the session secret, used to protect the Flask session. You should
46 # use a longer secret string known only to your application
47 # details are beyond the scope of this example
48 SECRET_KEY = "abc123!"
49
50 APP_CLIENT_ID = "<CLIENT_ID>"
51 APP_CLIENT_SECRET = "<CLIENT_SECRET>"
52
53 Shared Utilities
54 ~~~~~~~~~~~~~~~~
55
56 Some pieces that are of use for both parts of this flow.
57
58 First, you'll need to install ``Flask`` and the ``globus-sdk``.
59 Assuming you want to do so into a fresh virtualenv:
60
61 .. code-block:: bash
62
63 $ virtualenv example-venv
64 ...
65 $ source example-venv/bin/activate
66 $ pip install flask globus-sdk
67 ...
68
69 You'll also want a shared function for loading the SDK ``AuthClient`` which
70 represents your application, as you'll need it in a couple of places. Create
71 it, along with the definition for your Flask app, in ``example_app.py``:
72
73 .. code-block:: python
74
75 from flask import Flask, url_for, session, redirect, request
76 import globus_sdk
77
78 app = Flask(__name__)
79 app.config.from_pyfile("example_app.conf")
80
81
82 # actually run the app if this is called as a script
83 if __name__ == "__main__":
84 app.run()
85
86
87 def load_app_client():
88 return globus_sdk.ConfidentialAppAuthClient(
89 app.config["APP_CLIENT_ID"], app.config["APP_CLIENT_SECRET"]
90 )
91
92 Login
93 ~~~~~
94
95 Let's add login functionality to the end of ``example_app.py``, along with a
96 basic index page:
97
98 .. code-block:: python
99
100 @app.route("/")
101 def index():
102 """
103 This could be any page you like, rendered by Flask.
104 For this simple example, it will either redirect you to login, or print
105 a simple message.
106 """
107 if not session.get("is_authenticated"):
108 return redirect(url_for("login"))
109 return "You are successfully logged in!"
110
111
112 @app.route("/login")
113 def login():
114 """
115 Login via Globus Auth.
116 May be invoked in one of two scenarios:
117
118 1. Login is starting, no state in Globus Auth yet
119 2. Returning to application during login, already have short-lived
120 code from Globus Auth to exchange for tokens, encoded in a query
121 param
122 """
123 # the redirect URI, as a complete URI (not relative path)
124 redirect_uri = url_for("login", _external=True)
125
126 client = load_app_client()
127 client.oauth2_start_flow(redirect_uri)
128
129 # If there's no "code" query string parameter, we're in this route
130 # starting a Globus Auth login flow.
131 # Redirect out to Globus Auth
132 if "code" not in request.args:
133 auth_uri = client.oauth2_get_authorize_url()
134 return redirect(auth_uri)
135 # If we do have a "code" param, we're coming back from Globus Auth
136 # and can start the process of exchanging an auth code for a token.
137 else:
138 code = request.args.get("code")
139 tokens = client.oauth2_exchange_code_for_tokens(code)
140
141 # store the resulting tokens in the session
142 session.update(tokens=tokens.by_resource_server, is_authenticated=True)
143 return redirect(url_for("index"))
144
145 Logout
146 ~~~~~~
147
148 Logout is very simple -- it's just a matter of cleaning up the session. It does
149 the added work of cleaning up any tokens you fetched by invalidating them in
150 Globus Auth beforehand:
151
152 .. code-block:: python
153
154 @app.route("/logout")
155 def logout():
156 """
157 - Revoke the tokens with Globus Auth.
158 - Destroy the session state.
159 - Redirect the user to the Globus Auth logout page.
160 """
161 client = load_app_client()
162
163 # Revoke the tokens with Globus Auth
164 for token in (
165 token_info["access_token"] for token_info in session["tokens"].values()
166 ):
167 client.oauth2_revoke_token(token)
168
169 # Destroy the session state
170 session.clear()
171
172 # the return redirection location to give to Globus AUth
173 redirect_uri = url_for("index", _external=True)
174
175 # build the logout URI with query params
176 # there is no tool to help build this (yet!)
177 globus_logout_url = (
178 "https://auth.globus.org/v2/web/logout"
179 + "?client={}".format(app.config["PORTAL_CLIENT_ID"])
180 + "&redirect_uri={}".format(redirect_uri)
181 + "&redirect_name=Globus Example App"
182 )
183
184 # Redirect the user to the Globus Auth logout page
185 return redirect(globus_logout_url)
186
187
188 Using the Tokens
189 ~~~~~~~~~~~~~~~~
190
191 Using the tokens thus acquired is a simple matter of pulling them out of the
192 session and putting one into an ``AccessTokenAuthorizer``.
193 For example, one might do the following:
194
195 .. code-block:: python
196
197 authorizer = globus_sdk.AccessTokenAuthorizer(
198 session["tokens"]["transfer.api.globus.org"]["access_token"]
199 )
200 transfer_client = globus_sdk.TransferClient(authorizer=authorizer)
201
202 print("Endpoints belonging to the current logged-in user:")
203 for ep in transfer_client.endpoint_search(filter_scope="my-endpoints"):
204 print("[{}] {}".format(ep["id"], ep["display_name"]))