Giter VIP home page Giter VIP logo

bottle-jwt's Introduction

bottle_jwt: JSON Web Token authentication plugin for bottle.py

https://travis-ci.org/agile4you/bottle-jwt.svg?branch=master https://coveralls.io/repos/agile4you/bottle-jwt/badge.svg?branch=master&service=github

Example Usage

import bottle
from bottle_jwt import (JWTProviderPlugin, jwt_auth_required)


app = bottle.Bottle()

server_secret = '*Y*^%JHg7623'


class AuthBackend(object):
    """Implementing an auth backend class with at least two methods.
    """
    user = {'id': 1237832, 'username': 'pav', 'password': '123', 'data': {'sex': 'male', 'active': True}}

    def authenticate_user(self, username, password):
        """Authenticate User by username and password.

        Returns:
            A dict representing User Record or None.
        """
        if username == self.user['username'] and password == self.user['password']:
            return self.user
        return None

    def get_user(self, user_id):
        """Retrieve User By ID.

        Returns:
            A dict representing User Record or None.
        """
        if user_id == self.user['id']:
            return {k: self.user[k] for k in self.user if k != 'password'}
        return None


provider_plugin = JWTProviderPlugin(
    keyword='jwt',
    auth_endpoint='/auth',
    backend=AuthBackend(),
    fields=('username', 'password'),
    secret=server_secret,
    ttl=30
)

app.install(provider_plugin)


@app.get('/')
@jwt_auth_required
def private_resource():
    return {"scope": "For your eyes only!", "user": bottle.request.get_user()}


bottle.run(app=app, port=9092, host='0.0.0.0', reloader=True)

Registered endpoints:

- POST /auth - d {"username": <username>, "password": <password>}.
    *Returns a JSON object*: {"token": <auth_token>}

- GET / -headers Authorization: JWT <auth_token>.

bottle-jwt's People

Contributors

andersou avatar markusgraube avatar martinrm77 avatar mitchins avatar pyb1l avatar skinner927 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

bottle-jwt's Issues

Return Binary AKA Image Data

this could be me, but it seems like the callback handler returns a force mime-type of application/json-text

`class JSONPlugin(object):
name = 'json'
api = 2

def __init__(self, json_dumps=json_dumps):
    self.json_dumps = json_dumps

def apply(self, callback, route):
    dumps = self.json_dumps
    if not dumps: return callback
    def wrapper(*a, **ka):
        try:
            rv = callback(*a, **ka)
        except HTTPError:
            rv = _e()

        if isinstance(rv, dict):
            #Attempt to serialize, raises exception on failure
            json_response = dumps(rv)
            #Set content type only if serialization succesful
            response.content_type = 'application/json'
            return json_response
        elif isinstance(rv, HTTPResponse) and isinstance(rv.body, dict):
            rv.body = dumps(rv.body)
            rv.content_type = 'application/json'
        return rv

    return wrapper`

I figure either I'm misusing it and I can override the callback to not do this if I know the mime type - or I can add it as a feature (happy to do either), just need some advice please.

no Attribute signature

Hello i want to implement bottle jwt to authenticate mosquitto client using the broker.
I used python 2.7, when i run bottle its running correctly. The mosquitto configuration too. But when i try to run to publish using username and password using this command mosquitto_pub -t "test" -m "hola_mundo" -u andri -P andri123. When i used this command i have some error
In bottle terminal,
Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/bottle.py", line 862, in _handle return route.call(**args) File "/usr/local/lib/python2.7/dist-packages/bottle.py", line 189, in __get__ value = obj.__dict__[self.func.__name__] = self.func(obj) File "/usr/local/lib/python2.7/dist-packages/bottle.py", line 492, in call return self._make_callback() File "/usr/local/lib/python2.7/dist-packages/bottle.py", line 528, in _make_callback callback = plugin.apply(callback, context) File "/home/andri/Documents/bottle-jwt/bottle_jwt/auth.py", line 242, in apply signature = inspect.signature(callback).parameters AttributeError: 'module' object has no attribute 'signature' 127.0.0.1 - - [29/Mar/2017 14:44:17] "POST /auth HTTP/1.1" 500 745

Can you help me about my error ?
Thank's for advance

In mosquitto =

bottle-jwt isn't stateless

First, thanks for putting bottle-jwt in the open! It really helped me.
However, there is one thing which I think might be improved.

JWTs are a great authentication mechanism. They give you a structured and stateless way to declare a user and what they can access. They can be cryptographically signed and encrypted to prevent tampering on the client side.

From https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage.

In this plugin's code it is not the case. Suppose I want to store my user info in some kind of persistent storage, then I implement a custom backend which saves the info to let's say MongoDB.

Every time the plugin validates the token it calls:

user = self.backend.get_user(...)

Which calls the database. This isn't stateless, and further. It retrieves information which should already found in the token itself.

IMHO user = self.backend.get_user(...) should only be called in create_token
and validate should only validate with jwt.decode

Help about how to use it

Hello folks,

I try to use this plugin with bottle to create a simple web API, I am using debian 8 in a raspberrypi and I did install by pip.
Unfortunately I cant do it work, when I POST /auth?username=pav&password=123 I have 200 (OK) as return, but the token it is empty. Is there some issue about the version that I used?
I am new to python and manly bottle, sorry if it is the wrong place to make question.

Congratulations on the excellent project, regards.
Fabiano

How to refresh token

HI, thanks for this component, very good work.

Is it possible to provide an exemple to show the best way to refresh token from the client before expiration ?

Thanks

How to add custom claims in JWT payload?

bottle-jwt is really great :)

I would really like if I could add some custom payload to JWT. So that the client can have some extra information.

What about if the whole dict representing a user returned by authenticate_user of the AuthProvider would be used as JWT payload? Currently, only the field id of this dict is used. Or do I miss something?

Example FakeBackend in readme dont work

You need a better example with the correct function (not get_user, but authenticate_user and get_user) and return a string from authenticate_user instead of dict.

A little bit better documentation on the BaseBackend would also help using this plugin

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.