Skip to content

Commit

Permalink
examples
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelgrinberg committed Mar 13, 2016
1 parent 6c3f94d commit 609806a
Show file tree
Hide file tree
Showing 3 changed files with 164 additions and 0 deletions.
38 changes: 38 additions & 0 deletions examples/basic_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#!/usr/bin/env python
"""Basic authentication example
This example demonstrates how to protect Flask endpoints with basic
authentication, using secure hashed passwords.
After running this example, visit http://localhost:5000 in your browser. To
gain access, you can use (username=john, password=hello) or
(username=susan, password=bye).
"""
from flask import Flask
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
auth = HTTPBasicAuth()

users = {
"john": generate_password_hash("hello"),
"susan": generate_password_hash("bye")
}


@auth.verify_password
def verify_password(username, password):
if username in users:
return check_password_hash(users.get(username), password)
return False


@app.route('/')
@auth.login_required
def index():
return "Hello, %s!" % auth.username()


if __name__ == '__main__':
app.run()
69 changes: 69 additions & 0 deletions examples/multi_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#!/usr/bin/env python
"""Multiple authentication example
This example demonstrates how to combine two authentication methods using the
"MultiAuth" class.
The root URL for this application can be accessed via basic auth, providing
username and password, or via token auth, providing a bearer JWT token.
"""
from flask import Flask, g
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as JWT


app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'
jwt = JWT(app.config['SECRET_KEY'], expires_in=3600)

basic_auth = HTTPBasicAuth()
token_auth = HTTPTokenAuth('Bearer')
multi_auth = MultiAuth(basic_auth, token_auth)


def get_jwt(username, expires_in=3600):
return jwt.dumps({'username': username})


users = {
"john": generate_password_hash("hello"),
"susan": generate_password_hash("bye")
}

for user in users.keys():
token = jwt.dumps({'username': user})
print('*** token for {}: {}\n'.format(user, token))


@basic_auth.verify_password
def verify_password(username, password):
g.user = None
if username in users:
if check_password_hash(users.get(username), password):
g.user = username
return True
return False


@token_auth.verify_token
def verify_token(token):
g.user = None
try:
data = jwt.loads(token)
except:
return False
if 'username' in data:
g.user = data['username']
return True
return False


@app.route('/')
@multi_auth.login_required
def index():
return "Hello, %s!" % g.user


if __name__ == '__main__':
app.run()
57 changes: 57 additions & 0 deletions examples/token_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/usr/bin/env python
"""Token authentication example
This example demonstrates how to protect Flask endpoints with token
authentication, using JWT tokens.
When this application starts, a token is generated for each of the two users.
To gain access, you can use a command line HTTP client such as curl, passing
one of the tokens:
curl -X GET -H "Authorization: Bearer <insert-jwt-token-here>" http://localhost:5000/
The response should include the username, which is obtained from the JWT token.
"""
from flask import Flask, g
from flask_httpauth import HTTPBasicAuth, HTTPTokenAuth, MultiAuth
from itsdangerous import TimedJSONWebSignatureSerializer as JWT


app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'
jwt = JWT(app.config['SECRET_KEY'], expires_in=3600)

auth = HTTPTokenAuth('Bearer')


def get_jwt(username, expires_in=3600):
return jwt.dumps({'username': username})


users = ['john', 'susan']
for user in users:
token = jwt.dumps({'username': user})
print('*** token for {}: {}\n'.format(user, token))


@auth.verify_token
def verify_token(token):
g.user = None
try:
data = jwt.loads(token)
except:
return False
if 'username' in data:
g.user = data['username']
return True
return False


@app.route('/')
@auth.login_required
def index():
return "Hello, %s!" % g.user


if __name__ == '__main__':
app.run()

0 comments on commit 609806a

Please sign in to comment.