你如何在Flask中实现令牌认证? [英] How do you implement token authentication in Flask?

查看:282
本文介绍了你如何在Flask中实现令牌认证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让用户使用他们的帐户从一个单独的Web服务登录到我的Flask应用程序。我可以联系这个Web服务的API,并收到一个安全令牌。如何使用此令牌来验证用户,以便他们有权限访问?



我不需要将用户保存到我自己的数据库中。我只想验证他们的会议。我相信这可以使用Flask-Security和@auth_token_required装饰器来完成,但文档不是很详细,我不知道如何实现这个。



编辑:



以下是一个代码示例:

$ p $ @ main.route( / login,methods = [GET,POST])
def login():

payload = {User:john,Password:password123 }
url =http:// webserviceexample / api / login
headers = {'content-type':'application / json'})

#login to Web服务
r = requests.post(url,headers = headers,json = payload)
response = r.json()
$ b $ if(r.status_code是200):
token = response ['user'] ['authentication_token']

#允许用户进入保护视图

返回render_template(login.html,form = form )


@ main.route('/ protected')
@auth_token_required
def protected():
return render_template 'protected.html')


解决方案

<> / p>

看起来你的用例很简单,我们可以自己实现这个。在下面的代码中,我将在用户会话中存储您的令牌并检入新的包装器。让我们开始制作我们自己的包装器,我通常只是把它们放在一个wrappers.py文件中,但是你可以把它放在你喜欢的地方。

  def require_api_token(func):
@wrap(func)
def check_token(* args,** kwargs):
#检查是否在他们的会话中
如果'api_session_token'不在会话中:
#如果它没有返回我们的访问被拒绝的消息(你也可以返回一个重定向或者render_template)
返回响应(拒绝访问)

#否则只发送他们想去的地方
返回func(* args,** kwargs)

返回check_token

酷!

现在我们已经实现了包装器,会话。超级简单。让我们来修改你的函数...

$ $ $ $ $ $ $ $ $ $ @ $ main.route(/ login,methods = [GET,POST ))
def login():

payload = {User:john,Password:password123}
url =http:// webserviceexample / api / login
headers = {'content-type':'application / json'})

#登录到web服务
r = requests.post(url,如果(r.status_code是200):
token = response ['user'] ['header = header,json = payload]
response = r.json()

authentication_token']

#将导入移动到文件顶部!
从烧瓶导入会话

#把它放在会话
session ['api_session_token'] =令牌

#允许用户进入保护视图

return render_template(login.html,form = form)

可以使用@require_api_token包装检查受保护的视图,像这样...

  @ main.route('/ super_secret') 
@require_api_token
def super_secret():
returnSssshhh,这是个秘密

编辑
哇!我忘了提及你需要在你的应用程序配置中设置你的SECRET_KEY。



只要一个SECRET_KEY =SOME_RANDOM_STRING的config.py文件就可以了。然后加载它...

  main.config.from_object(config)


I'm trying to allow users to login to my Flask app using their accounts from a separate web service. I can contact the api of this web service and receive a security token. How do I use this token to authenticate users so that they have access to restricted views?

I don't need to save users into my own database. I only want to authenticate them for a session. I believe this can be done using Flask-Security and the @auth_token_required decorator but the documentation is not very detailed and I'm not sure how to implement this.

EDIT:

Here's a code example:

@main.route("/login", methods=["GET", "POST"])
def login():

    payload = {"User": "john", "Password": "password123"}
    url = "http://webserviceexample/api/login"
    headers = {'content-type': 'application/json'})

    #login to web service
    r = requests.post(url, headers=headers, json=payload)
    response = r.json()

    if (r.status_code is 200):
        token = response['user']['authentication_token']

        # allow user into protected view

    return render_template("login.html", form=form)


@main.route('/protected')
@auth_token_required
def protected():
    return render_template('protected.html')

解决方案

Hey there Amedrikaner!

It looks like your use-case is simple enough that we can implement this ourselves. In the code below, I'll be storing your token in the users session and checking in a new wrapper. Let's get started by making our own wrapper, I usually just put these in a wrappers.py file but can you can place it where you like.

def require_api_token(func):
    @wraps(func)
    def check_token(*args, **kwargs):
        # Check to see if it's in their session
        if 'api_session_token' not in session:
            # If it isn't return our access denied message (you can also return a redirect or render_template)
            return Response("Access denied")

        # Otherwise just send them where they wanted to go
        return func(*args, **kwargs)

    return check_token

Cool!

Now we've got our wrapper implemented we can just save their token to the session. Super simple. Let's modify your function...

@main.route("/login", methods=["GET", "POST"])
def login():

    payload = {"User": "john", "Password": "password123"}
    url = "http://webserviceexample/api/login"
    headers = {'content-type': 'application/json'})

    #login to web service
    r = requests.post(url, headers=headers, json=payload)
    response = r.json()

    if (r.status_code is 200):
        token = response['user']['authentication_token']

        # Move the import to the top of your file!
        from flask import session

        # Put it in the session
        session['api_session_token'] = token

        # allow user into protected view

    return render_template("login.html", form=form)

Now you can check the protected views using the @require_api_token wrapper, like this...

@main.route('/super_secret')
@require_api_token
def super_secret():
    return "Sssshhh, this is a secret"

EDIT Woah! I forgot to mention you need to set your SECRET_KEY in your apps config.

Just a config.py file with SECRET_KEY="SOME_RANDOM_STRING" will do. Then load it with...

main.config.from_object(config)

这篇关于你如何在Flask中实现令牌认证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆