简体   繁体   English

使用bottle-jwt装饰器出现问题(无效)

[英]Trouble using bottle-jwt decorator (not works)



Having soe trouble using this plugin https://github.com/agile4you/bottle-jwt/ 在使用此插件时遇到麻烦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!"]}" 运行后,如果我打开浏览器,在127.0.0.1/8080上,我将返回一个空白页面,其中包含字符串“ {“ AuthError”:[“无法访问该资源!”]}“
Wich is Fine, it means that i'm not allowed to open index.html file (Cool: @jwt_auth_required worked) Wich很好,这意味着不允许我打开index.html文件(很酷:@jwt_auth_required有效)
Digging in source file i found a function named validate_token() with: 在源文件中,我发现了一个名为validate_token()的函数,该函数具有:

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? 因此,如果令牌不匹配或缺少令牌,有什么办法可以在我的login.html页面上重定向我? Plugin includes some way to do that or is just an API pckg? 插件包含执行此操作的某种方式,或者仅仅是API pckg?


thanks for your time 谢谢你的时间
Hele. 饸饹。

That's not how JWT concept is supposed to be used. 这不是应该使用JWT概念的方式。 JWT are for RESTFul. JWT用于RESTFul。

You need to make the server as REST API and on the client use JS libraries such as AngularJs / Vue.js etc., 您需要使服务器成为REST API,并且在客户端上使用JS库(例如AngularJs / Vue.js等),

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. auth_endpoint ='/ login'用于提供自定义的端点进行授权,其中Bottle_JWT方法正在寻找用于验证并为其生成JWT的凭据。

I created a mock just to construct a response and this is how it should be used. 我创建了一个模拟,仅用于构建响应,这就是应该如何使用它。

在此处输入图片说明

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 传递正确的凭据后,插件将以JWT响应并过期,您必须在授权调用中进行拦截并添加为请求标头

在此处输入图片说明

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM