• Stars
    star
    905
  • Rank 50,477 (Top 1.0 %)
  • Language
    Python
  • License
    MIT License
  • Created almost 11 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Example application for my RESTful Authentication with Flask article.

REST-auth

Companion application to my RESTful Authentication with Flask article.

Installation

After cloning, create a virtual environment and install the requirements. For Linux and Mac users:

$ virtualenv venv
$ source venv/bin/activate
(venv) $ pip install -r requirements.txt

If you are on Windows, then use the following commands instead:

$ virtualenv venv
$ venv\Scripts\activate
(venv) $ pip install -r requirements.txt

Running

To run the server use the following command:

(venv) $ python api.py
 * Running on http://127.0.0.1:5000/
 * Restarting with reloader

Then from a different terminal window you can send requests.

API Documentation

  • POST /api/users

    Register a new user.
    The body must contain a JSON object that defines username and password fields.
    On success a status code 201 is returned. The body of the response contains a JSON object with the newly added user. A Location header contains the URI of the new user.
    On failure status code 400 (bad request) is returned.
    Notes:

    • The password is hashed before it is stored in the database. Once hashed, the original password is discarded.
    • In a production deployment secure HTTP must be used to protect the password in transit.
  • GET /api/users/<int:id>

    Return a user.
    On success a status code 200 is returned. The body of the response contains a JSON object with the requested user.
    On failure status code 400 (bad request) is returned.

  • GET /api/token

    Return an authentication token.
    This request must be authenticated using a HTTP Basic Authentication header.
    On success a JSON object is returned with a field token set to the authentication token for the user and a field duration set to the (approximate) number of seconds the token is valid.
    On failure status code 401 (unauthorized) is returned.

  • GET /api/resource

    Return a protected resource.
    This request must be authenticated using a HTTP Basic Authentication header. Instead of username and password, the client can provide a valid authentication token in the username field. If using an authentication token the password field is not used and can be set to any value.
    On success a JSON object with data for the authenticated user is returned.
    On failure status code 401 (unauthorized) is returned.

Example

The following curl command registers a new user with username miguel and password python:

$ curl -i -X POST -H "Content-Type: application/json" -d '{"username":"miguel","password":"python"}' http://127.0.0.1:5000/api/users
HTTP/1.0 201 CREATED
Content-Type: application/json
Content-Length: 27
Location: http://127.0.0.1:5000/api/users/1
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 19:56:39 GMT

{
  "username": "miguel"
}

These credentials can now be used to access protected resources:

$ curl -u miguel:python -i -X GET http://127.0.0.1:5000/api/resource
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 30
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 20:02:25 GMT

{
  "data": "Hello, miguel!"
}

Using the wrong credentials the request is refused:

$ curl -u miguel:ruby -i -X GET http://127.0.0.1:5000/api/resource
HTTP/1.0 401 UNAUTHORIZED
Content-Type: text/html; charset=utf-8
Content-Length: 19
WWW-Authenticate: Basic realm="Authentication Required"
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 20:03:18 GMT

Unauthorized Access

Finally, to avoid sending username and password with every request an authentication token can be requested:

$ curl -u miguel:python -i -X GET http://127.0.0.1:5000/api/token
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 139
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 20:04:15 GMT

{
  "duration": 600,
  "token": "eyJhbGciOiJIUzI1NiIsImV4cCI6MTM4NTY2OTY1NSwiaWF0IjoxMzg1NjY5MDU1fQ.eyJpZCI6MX0.XbOEFJkhjHJ5uRINh2JA1BPzXjSohKYDRT472wGOvjc"
}

And now during the token validity period there is no need to send username and password to authenticate anymore:

$ curl -u eyJhbGciOiJIUzI1NiIsImV4cCI6MTM4NTY2OTY1NSwiaWF0IjoxMzg1NjY5MDU1fQ.eyJpZCI6MX0.XbOEFJkhjHJ5uRINh2JA1BPzXjSohKYDRT472wGOvjc:x -i -X GET http://127.0.0.1:5000/api/resource
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 30
Server: Werkzeug/0.9.4 Python/2.7.3
Date: Thu, 28 Nov 2013 20:05:08 GMT

{
  "data": "Hello, miguel!"
}

Once the token expires it cannot be used anymore and the client needs to request a new one. Note that in this last example the password is arbitrarily set to x, since the password isn't used for token authentication.

An interesting side effect of this implementation is that it is possible to use an unexpired token as authentication to request a new token that extends the expiration time. This effectively allows the client to change from one token to the next and never need to send username and password after the initial token was obtained.

Change Log

v0.3 - Return token duration.

v0.2 - Return a 201 status code and Location header from /api/users endpoint.

v0.1 - Initial release.

More Repositories

1

flasky

Companion code to my O'Reilly book "Flask Web Development", second edition.
Python
8,256
star
2

Flask-SocketIO

Socket.IO integration for Flask applications.
Python
5,111
star
3

microblog

A microblogging web application written in Python and Flask that I developed as part of my Flask Mega-Tutorial series.
Python
4,297
star
4

python-socketio

Python Socket.IO server and client
Python
3,742
star
5

Flask-Migrate

SQLAlchemy database migrations for Flask applications using Alembic
Python
2,243
star
6

flask-video-streaming

Supporting code for my article on video streaming with Flask.
Python
1,353
star
7

microdot

The impossibly small web framework for Python and MicroPython.
Python
1,326
star
8

Flask-HTTPAuth

Simple extension that provides Basic, Digest and Token HTTP authentication for Flask routes
Python
1,206
star
9

flask-celery-example

This repository contains the example code for my blog article Using Celery with Flask.
Python
1,171
star
10

REST-tutorial

Files for my REST API tutorials featuring a server written in Python and a web client written in Javascript.
HTML
656
star
11

Flask-SocketIO-Chat

A simple chat application that demonstrates how to structure a Flask-SocketIO application.
Python
639
star
12

flack

Companion code to my PyCon 2016 "Flask at Scale" tutorial session.
Python
502
star
13

Flask-Moment

Formatting of dates and times in Flask templates using moment.js.
Python
364
star
14

microblog-api

A modern (as of 2023) Flask API back end.
Python
345
star
15

APIFairy

A minimalistic API framework built on top of Flask, Marshmallow and friends.
Python
316
star
16

turbo-flask

Integration of Hotwire's Turbo library with Flask.
Python
291
star
17

flasky-with-celery

How to incorporate Celery into a well structured Flask application
Python
279
star
18

flask-tables

Beautiful Interactive tables in your Flask templates.
Python
272
star
19

react-flask-app

A Flask + React demo application.
JavaScript
266
star
20

flask-sock

WebSocket support without gevent for Flask and other WSGI frameworks.
Python
247
star
21

Flask-PageDown

Implementation of StackOverflow's "PageDown" markdown editor for Flask and Flask-WTF.
Python
240
star
22

flask-oauth-example

Example code from my "OAuth Authentication with Flask" article.
Python
238
star
23

python-engineio

Python Engine.IO server and client
Python
224
star
24

flasky-first-edition

Companion code to the first edition of my O'Reilly book "Flask Web Development".
Python
218
star
25

promisio

JavaScript-style async programming for Python.
Python
210
star
26

aioflask

Flask running on asyncio!
Python
200
star
27

oreilly-flask-apis-video

This repository contains the software that accompanies my O'Reilly training video "Building Web APIs with Flask".
Python
192
star
28

api-pycon2015

Code for my PyCon talk "Is Your REST API RESTful?"
Python
154
star
29

oreilly-intro-to-flask-video

This repository contains the software that accompanies my O'Reilly training video "An Introduction to Flask".
Python
152
star
30

greenletio

Asyncio integration with sync code using greenlets.
Python
146
star
31

flask-pycon2014

Code for my PyCon 2014 tutorial "Flask By Example"
Python
145
star
32

merry

Decorator based error handling for Python
Python
144
star
33

two-factor-auth-flask

Example application for my "Two Factor Authentication with Flask" blog article.
Python
143
star
34

api-pycon2014

Code for my PyCon talk "Writing RESTful Web Services with Flask"
Python
121
star
35

flask-twilio-video

A small video conference application using Flask and Twilio Programmable Video
JavaScript
119
star
36

alchemical

SQLAlchemy 2.0+ wrapper that simplifies its use in Python applications. Can be used on its own or alongside Flask, FastAPI or other web frameworks.
Python
117
star
37

flask-gridjs

Beautiful Interactive tables in your Flask templates using grid.js.
HTML
107
star
38

flask-examples

Code for my "Python Web Development with Flask" presentation.
Python
99
star
39

socketio-examples

A few examples that demonstrate the features of the Python Socket.IO server
JavaScript
89
star
40

microflack_admin

Shell
86
star
41

flask-paranoid

Simple user session protection
Python
74
star
42

retrofun

Code from my "SQLAlchemy 2 In Practice" book.
Python
72
star
43

slam

Serverless deployment of Python APIs
Python
70
star
44

simple-websocket

Simple WebSocket server and client for Python.
Python
69
star
45

quick-socketio-tutorial

Python
68
star
46

sqlalchemy-soft-delete

Implementation of soft deletes for Flask and SQLAlchemy
Python
67
star
47

flask-pycon2015

Code for my PyCon 2015 tutorial "Flask Workshop"
Python
63
star
48

react-microblog

Code for my React Mega-Tutorial course.
JavaScript
61
star
49

django-verify

Extending the Django authentication system with a phone verification step.
Python
53
star
50

anaglyph.py

3D Anaglyph image generator
Python
48
star
51

heat-tutorial

Supporting files for my "OpenStack Orchestration in Depth" tutorial.
41
star
52

climax

A lightweight argparse wrapper inspired by click.
Python
40
star
53

Flask-Runner

A set of standard command line arguments for Flask applications
Python
40
star
54

michelino

A firmware for Arduino based remote controlled robot vehicles.
C++
39
star
55

look-ma-no-http

Code from my EuroPython 2019 talk "Look Ma, No HTTP!"
Python
37
star
56

flask-webcast

Code from my O'Reilly webcast "Python Web Development with Flask"
Python
36
star
57

flask-react-twilio-chat

A chat application based on the Twilio Conversations API with a Flask back end and a React front end.
JavaScript
31
star
58

mylang

The "my" programming language from my toy language tutorial.
Python
31
star
59

flask-stripe-orders

Python
29
star
60

microblog-verify

Microblog application from the Flask Mega-Tutorial with added two-factor authentication via the Twilio Verify API.
Python
28
star
61

microblog-authy

Microblog application from the Flask Mega-Tutorial with added two-factor push authentication via Authy
Python
27
star
62

asyncio-testing

Unit testing asyncio code
Python
27
star
63

microflack_common

Python
26
star
64

micropython-iot-tutorial

Source code for the "MicroPython and the Internet of Things" tutorial by Miguel Grinberg
Python
25
star
65

aio-executor

A concurrent.futures.Executor implementation that runs asynchronous tasks in an asyncio loop.
Python
22
star
66

eudcc-decoder

React application that scans, decodes and validates EU Digital COVID-19 certificates, all in the browser.
JavaScript
21
star
67

flask-phone-input

An example application that shows how to integrate the intTelInput.js library with Flask and Flask-WTF.
HTML
20
star
68

flask-webauthn-demo

HTML
20
star
69

microflack_users

Python
19
star
70

microflack_ui

JavaScript
19
star
71

twilio-serverless-video

JavaScript
18
star
72

circular-dependencies-webcast

Example code for my webcast on circular dependencies in Python
Python
18
star
73

react-microblog-ts

A version of the React Mega-Tutorial project adapted to TypeScript
TypeScript
18
star
74

webcast-assistant

A little Flask + React application that helps me host live streaming events
JavaScript
17
star
75

easy-cli

Easy, yet powerful, command line configuration based on zsh, tmux and vim.
Vim Script
17
star
76

sendgrid-flask-mail

An example Flask and Flask-Mail application that sends emails through Twilio SendGrid
Python
16
star
77

python-testing

Code from my Python unit testing blog articles
Python
16
star
78

microflack_tokens

Python
16
star
79

twilio-send-sms-demo

Python
16
star
80

easy-etcd

Start an etcd cluster with ease!
Shell
16
star
81

microflack_socketio

Python
16
star
82

microflack_messages

Python
14
star
83

flatdoc

Flat documentation generator
Python
14
star
84

flask-live-coding-webcast

This repository contains the code I wrote during my O'Reilly webcast "Let's Build a Web Application!"
Python
13
star
85

cygwin-installer

A script that simplifies the installation of Cygwin
Batchfile
12
star
86

flask-preact

An example integration between Flask and the Preact front end library.
HTML
12
star
87

easy-lb-haproxy

Simple load balancer container for Docker based on haproxy, confd and etcd
Shell
12
star
88

twilio-api-explorer

An interactive browser for Twilio's OpenAPI specs.
JavaScript
10
star
89

Flask-MarrowMailer

Marrow Mailer integration for Flask.
Python
9
star
90

twilio-serverless-video-call

A simple video calling application hosted on the Twilio serverless platform
JavaScript
9
star
91

micropython-esp8266-vagrant

A virtual machine that simplifies building MicroPython for the ESP8266 microcontroller.
Shell
9
star
92

Flask-Intro

Sample code from my "Introduction to Flask" presentation.
Python
8
star
93

flask-token-auth-demo

7
star
94

microblog-2012

Microblog application for the original Flask Mega-Tutorial from 2012
Python
7
star
95

micropython-pico-code

Code for my MicroPython with the Raspberry Pi Pico book.
Python
7
star
96

arduino-digital-picture-frame

An Arduino digital picture frame server, with a Python client for it.
Python
6
star
97

easy-lb-nginx

Simple load balancer container based on nginx, confd and etcd
Shell
6
star
98

microblog-2018

The 2018 and 2021 versions of the microblog project of the Flask Mega-Tutorial
Python
6
star
99

live-screen-sharing

JavaScript
5
star
100

softcover-for-docker

Docker container image for the softcover toolchain for building ebooks.
Dockerfile
5
star