Token-Based Security in a REST API

Andy Balaam
artificialworlds.net/blog

Contents

Recap

Token-Based Security

Token-Based Security

$ curl -c c.txt \
    http://localhost:8080/api/v1/login \
    -u user1:pass1

$ curl -b c.txt \
    --data '{"titl...}' \
    http://localhost:8080/api/v1/poems

Logging in

class LogIn:
...
def GET( self ):
    user = require_authenticated_user(
        self.db )
    token = generate_token()
    self.db.tokens[token] =
        { "user": user }
    ...

Logging in

def GET( self ):
    ...
    web.setcookie(
        "authentication_token",
        token,
        expires=36000 # 10 hours
    )
    web.ctx.status = "204 No Content"

Logging in

def generate_token():
    # DO NOT COPY THIS CODE - NOT SECURE
    return str(
        random.randint( 0, 1000 ) )

Authentication

def authenticate_user( db ):
    authentication_token =
        web.cookies().get(
            "authentication_token" )

    user_from_token = authenticate_token(
        db, authentication_token )

    if user_from_token is not None:
        return user_from_token
    ...

Authentication

def authenticate_token( db, tok ):
    if tok is None:
        return None

    if tok in db.tokens:
        return db.tokens[tok]["user"]

TODOs

Why?

Why is this better than passing username and password?

Pros:

Why?

Why is this better than passing username and password?

Cons:

More info

Videos youtube.com/user/ajbalaam
Twitter @andybalaam
Blog artificialworlds.net/blog
Projects artificialworlds.net