Trouble using bottle-jwt decorator (not works)

Question:

Having some trouble using this plugin https://github.com/agile4you/bottle-jwt/

It seems to not work as I expected, down below my code:

import bottle
from Py.engine import *
from bottle_jwt import (JWTProviderPlugin, jwt_auth_required)

    class AuthBackend(object):
    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


app = bottle.Bottle()
server_secret = 'secret'

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

app.install(provider_plugin)

@app.route('/')
@jwt_auth_required
def index():
    return open('Html/index.html', 'r').read()


@app.post('/login')
def login():
    return open('Html/login.html', 'r').read()


@app.get('/login')
def login():
    return open('Html/login.html', 'r').read()


def run_server():
    bottle.run(app=app, host='localhost', port=8080, debug=True, reloader=True)


# Main
if __name__ == '__main__':
    run_server()

Once running, if I open browser On 127.0.0.1/8080 i get back a blank page with the string "{"AuthError": ["Cannot access this resource!"]}"

Which is Fine, it means that I’m not allowed to open index.html file (Cool: @jwt_auth_required worked)

Digging in source file I found a function named validate_token() with:

if not token:
   logger.debug("Forbidden access")
   raise JWTForbiddenError('Cannot access this resource!')

Here is the exception

except JWTForbiddenError as error:
       bottle.response.content_type = b('application/json')
       bottle.response._status_line = b('403 Forbidden')
       return {"AuthError": error.args}

So, is there any way to redirect me on my login.html page if token does not match or is absent?
Plugin includes some way to do that or is just an API pckg?

Asked By: Hele

||

Answers:

That’s not how JWT concept is supposed to be used. JWT are for RESTFul.

You need to make the server as REST API and on the client use JS
libraries such as AngularJs / Vue.js etc.,

Coming to the question about the plugin:

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

auth_endpoint=’/login’ is to give a custom endpoint for authorization where the Bottle_JWT methods are looking for credentials to validate and generate JWT for.

I created a mock just to construct a response and this is how it should be used.

enter image description here

Once you pass the correct credential, the plugin responds with the JWT and expire which you have to intercept in authorized calls and add as request headers

enter image description here

Hope this helps.

Answered By: Farhan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.