Skip to content

Commit 0ac84a1

Browse files
authored
Merge pull request #64 from auth0-samples/sdk-3183
2 parents 8db7481 + 2d460a2 commit 0ac84a1

File tree

9 files changed

+69
-248
lines changed

9 files changed

+69
-248
lines changed

01-Login/.env.example

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
11
AUTH0_CLIENT_ID={CLIENT_ID}
22
AUTH0_DOMAIN={DOMAIN}
3-
AUTH0_CLIENT_SECRET={CLIENT_SECRET}
4-
AUTH0_CALLBACK_URL=http://localhost:3000/callback
5-
AUTH0_AUDIENCE=
3+
APP_SECRET_KEY=ALongRandomlyGeneratedString

01-Login/README.md

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,16 @@ This sample demonstrates how to add authentication to a Python web app using Aut
44

55
# Running the App
66

7-
To run the sample, make sure you have `python` and `pip` installed.
7+
To run the sample, make sure you have `python3` and `pip` installed.
88

99
Rename `.env.example` to `.env` and populate it with the client ID, domain, secret, callback URL and audience for your
10-
Auth0 app. If you are not implementing any API you can use `https://YOUR_DOMAIN.auth0.com/userinfo` as the audience.
10+
Auth0 app. If you are not implementing any API you can use `https://YOUR_DOMAIN.auth0.com/userinfo` as the audience.
1111
Also, add the callback URL to the settings section of your Auth0 client.
1212

13-
Register `http://localhost:3000/callback` as `Allowed Callback URLs` and `http://localhost:3000`
13+
Register `http://localhost:3000/callback` as `Allowed Callback URLs` and `http://localhost:3000`
1414
as `Allowed Logout URLs` in your client settings.
1515

16-
Run `pip install -r requirements.txt` to install the dependencies and run `python server.py`.
16+
Run `pip install -r requirements.txt` to install the dependencies and run `python server.py`.
1717
The app will be served at [http://localhost:3000/](http://localhost:3000/).
1818

1919
# Running the App with Docker
@@ -24,15 +24,15 @@ To run the sample with [Docker](https://www.docker.com/), make sure you have `do
2424

2525
Rename the .env.example file to .env, change the environment variables, and register the URLs as explained [previously](#running-the-app).
2626

27-
Run `sh exec.sh` to build and run the docker image in Linux or run `.\exec.ps1` to build
27+
Run `sh exec.sh` to build and run the docker image in Linux or run `.\exec.ps1` to build
2828
and run the docker image on Windows.
2929

3030
## What is Auth0?
3131

3232
Auth0 helps you to:
3333

3434
* Add authentication with [multiple authentication sources](https://auth0.com/docs/identityproviders),
35-
either social like **Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, among others**,or
35+
either social like **Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, among others**,or
3636
enterprise identity systems like **Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider**.
3737
* Add authentication through more traditional **[username/password databases](https://docs.auth0.com/mysql-connection-tutorial)**.
3838
* Add support for **[linking different user accounts](https://auth0.com/docs/link-accounts)** with the same user.
@@ -49,7 +49,7 @@ enterprise identity systems like **Windows Azure AD, Google Apps, Active Directo
4949
## Issue Reporting
5050

5151
If you have found a bug or if you have a feature request, please report them at this repository issues section.
52-
Please do not report security vulnerabilities on the public GitHub issue tracker.
52+
Please do not report security vulnerabilities on the public GitHub issue tracker.
5353
The [Responsible Disclosure Program](https://auth0.com/whitehat) details the procedure for disclosing security issues.
5454

5555
## Author
@@ -58,4 +58,4 @@ The [Responsible Disclosure Program](https://auth0.com/whitehat) details the pro
5858

5959
## License
6060

61-
This project is licensed under the MIT license. See the [LICENSE](LICENCE) file for more info.
61+
This project is licensed under the MIT license. See the [LICENSE](../LICENSE) file for more info.

01-Login/constants.py

Lines changed: 0 additions & 11 deletions
This file was deleted.

01-Login/public/app.css

Lines changed: 0 additions & 98 deletions
This file was deleted.

01-Login/requirements.txt

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
flask
2-
python-dotenv
3-
requests
4-
authlib>=0.14.1
5-
six
1+
flask>=2.0.3
2+
python-dotenv>=0.19.2
3+
authlib>=1.0
4+
requests>=2.27.1

01-Login/server.py

Lines changed: 41 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,110 +1,74 @@
11
"""Python Flask WebApp Auth0 integration example
22
"""
3-
from functools import wraps
3+
44
import json
55
from os import environ as env
6-
from werkzeug.exceptions import HTTPException
7-
8-
from dotenv import load_dotenv, find_dotenv
9-
from flask import Flask
10-
from flask import jsonify
11-
from flask import redirect
12-
from flask import render_template
13-
from flask import session
14-
from flask import url_for
15-
from authlib.integrations.flask_client import OAuth
16-
from six.moves.urllib.parse import urlencode
6+
from urllib.parse import quote_plus, urlencode
177

18-
import constants
8+
from authlib.integrations.flask_client import OAuth
9+
from dotenv import find_dotenv, load_dotenv
10+
from flask import Flask, redirect, render_template, session, url_for
1911

2012
ENV_FILE = find_dotenv()
2113
if ENV_FILE:
2214
load_dotenv(ENV_FILE)
2315

24-
AUTH0_CALLBACK_URL = env.get(constants.AUTH0_CALLBACK_URL)
25-
AUTH0_CLIENT_ID = env.get(constants.AUTH0_CLIENT_ID)
26-
AUTH0_CLIENT_SECRET = env.get(constants.AUTH0_CLIENT_SECRET)
27-
AUTH0_DOMAIN = env.get(constants.AUTH0_DOMAIN)
28-
AUTH0_BASE_URL = 'https://' + AUTH0_DOMAIN
29-
AUTH0_AUDIENCE = env.get(constants.AUTH0_AUDIENCE)
30-
31-
app = Flask(__name__, static_url_path='/public', static_folder='./public')
32-
app.secret_key = constants.SECRET_KEY
33-
app.debug = True
34-
35-
36-
@app.errorhandler(Exception)
37-
def handle_auth_error(ex):
38-
response = jsonify(message=str(ex))
39-
response.status_code = (ex.code if isinstance(ex, HTTPException) else 500)
40-
return response
16+
app = Flask(__name__)
17+
app.secret_key = env.get("APP_SECRET_KEY")
4118

4219

4320
oauth = OAuth(app)
4421

45-
auth0 = oauth.register(
46-
'auth0',
47-
client_id=AUTH0_CLIENT_ID,
48-
client_secret=AUTH0_CLIENT_SECRET,
49-
api_base_url=AUTH0_BASE_URL,
50-
access_token_url=AUTH0_BASE_URL + '/oauth/token',
51-
authorize_url=AUTH0_BASE_URL + '/authorize',
22+
oauth.register(
23+
"auth0",
24+
client_id=env.get("AUTH0_CLIENT_ID"),
5225
client_kwargs={
53-
'scope': 'openid profile email',
26+
"scope": "openid profile email",
5427
},
28+
server_metadata_url=f'https://{env.get("AUTH0_DOMAIN")}/.well-known/openid-configuration',
5529
)
5630

5731

58-
def requires_auth(f):
59-
@wraps(f)
60-
def decorated(*args, **kwargs):
61-
if constants.PROFILE_KEY not in session:
62-
return redirect('/login')
63-
return f(*args, **kwargs)
64-
65-
return decorated
66-
67-
6832
# Controllers API
69-
@app.route('/')
33+
@app.route("/")
7034
def home():
71-
return render_template('home.html')
35+
return render_template(
36+
"home.html",
37+
session=session.get("user"),
38+
pretty=json.dumps(session.get("user"), indent=4),
39+
)
7240

7341

74-
@app.route('/callback')
75-
def callback_handling():
76-
auth0.authorize_access_token()
77-
resp = auth0.get('userinfo')
78-
userinfo = resp.json()
42+
@app.route("/callback", methods=["GET", "POST"])
43+
def callback():
44+
token = oauth.auth0.authorize_access_token()
45+
session["user"] = token
46+
return redirect("/")
7947

80-
session[constants.JWT_PAYLOAD] = userinfo
81-
session[constants.PROFILE_KEY] = {
82-
'user_id': userinfo['sub'],
83-
'name': userinfo['name'],
84-
'picture': userinfo['picture']
85-
}
86-
return redirect('/dashboard')
8748

88-
89-
@app.route('/login')
49+
@app.route("/login")
9050
def login():
91-
return auth0.authorize_redirect(redirect_uri=AUTH0_CALLBACK_URL, audience=AUTH0_AUDIENCE)
51+
return oauth.auth0.authorize_redirect(
52+
redirect_uri=url_for("callback", _external=True)
53+
)
9254

9355

94-
@app.route('/logout')
56+
@app.route("/logout")
9557
def logout():
9658
session.clear()
97-
params = {'returnTo': url_for('home', _external=True), 'client_id': AUTH0_CLIENT_ID}
98-
return redirect(auth0.api_base_url + '/v2/logout?' + urlencode(params))
99-
100-
101-
@app.route('/dashboard')
102-
@requires_auth
103-
def dashboard():
104-
return render_template('dashboard.html',
105-
userinfo=session[constants.PROFILE_KEY],
106-
userinfo_pretty=json.dumps(session[constants.JWT_PAYLOAD], indent=4))
59+
return redirect(
60+
"https://"
61+
+ env.get("AUTH0_DOMAIN")
62+
+ "/v2/logout?"
63+
+ urlencode(
64+
{
65+
"returnTo": url_for("home", _external=True),
66+
"client_id": env.get("AUTH0_CLIENT_ID"),
67+
},
68+
quote_via=quote_plus,
69+
)
70+
)
10771

10872

10973
if __name__ == "__main__":
110-
app.run(host='0.0.0.0', port=env.get('PORT', 3000))
74+
app.run(host="0.0.0.0", port=env.get("PORT", 3000))

01-Login/templates/dashboard.html

Lines changed: 0 additions & 23 deletions
This file was deleted.

01-Login/templates/home.html

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,16 @@
11
<html>
2-
<head>
3-
4-
<meta name="viewport" content="width=device-width, initial-scale=1">
5-
6-
<!-- font awesome from BootstrapCDN -->
7-
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
8-
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
9-
10-
<link href="/public/app.css" rel="stylesheet">
11-
</head>
12-
<body class="home">
13-
<div class="container">
14-
<div class="login-page clearfix">
15-
<div class="login-box auth0-box before">
16-
<img src="https://i.cloudup.com/StzWWrY34s.png" />
17-
<h3>Auth0 Example</h3>
18-
<p>Zero friction identity infrastructure, built for developers</p>
19-
<a id="qsLoginBtn" class="btn btn-primary btn-lg btn-login btn-block" href="/login">Log In</a>
20-
</div>
21-
</div>
22-
</div>
23-
</body>
2+
<head>
3+
<meta charset="utf-8" />
4+
<title>Auth0 Example</title>
5+
</head>
6+
<body>
7+
{% if session %}
8+
<h1>Welcome {{session.userinfo.name}}!</h1>
9+
<p><a href="/logout">Logout</a></p>
10+
<div><pre>{{pretty}}</pre></div>
11+
{% else %}
12+
<h1>Welcome Guest</h1>
13+
<p><a href="/login">Login</a></p>
14+
{% endif %}
15+
</body>
2416
</html>

0 commit comments

Comments
 (0)