【问题标题】:How to handle authentication in different flask microservices如何在不同的烧瓶微服务中处理身份验证
【发布时间】:2020-09-26 10:18:45
【问题描述】:

我对开发还很陌生。所以,对于可能愚蠢的问题,提前抱歉:

我正在尝试使用 2 个微服务实现一个简单的应用程序:

  1. User Api
  2. TODO Api

我已经开始实施 auth 部分,但遇到了一些我不理解且在网上找不到的东西。

在 User Api 中,我实现了一些端点和 jwt 身份验证。 这是控制器的示例。 所有的认证逻辑都隐藏在相应的装饰器@token_required@admin_token_required

from http import HTTPStatus
from flask_restplus import Namespace, Resource
from app.exceptions import FieldValidationException
from app.v1 import v1_api
from app.v1.main.model.UserModel import User
from app.v1.main.service.UserService import UserService
from utils.decorators import admin_token_required, token_required

ls_user_ns = Namespace("user")
@ls_user_ns.route("/")
class UserList(Resource):
    user_service = UserService()

    @ls_user_ns.marshal_with(
        User.get_user_response_model,
        code=HTTPStatus.OK,
        as_list=True,
        description="Get all users",
        envelope="users",
    )
    @admin_token_required
    def get(self):
        users = self.user_service.get_all_users()
        return users, HTTPStatus.OK

    @ls_user_ns.doc(body=User.create_user_request_model, validate=True)
    @ls_user_ns.marshal_with(
        User.create_user_response_model,
        code=HTTPStatus.CREATED,
        description="Create new user",
    )
    @token_required
    def post(self):
        payload = v1_api.payload
        user, exceptions = self.user_service.create_user(payload)
        if exceptions:
            raise FieldValidationException(exceptions)
        else:
            return user, HTTPStatus.CREATED

我还有另一个微服务,TODO Api。在这里,我还希望资源落后于身份验证。 即我想使用相同的 @token_required 装饰器,但来自用户 Api。 绕过它的最佳方法是什么? 我在网上找到的所有资源都以格式显示示例:一个文件中的所有内容或最佳案例场景,所有内容都拆分为模块,但在一个 API 中。 如果有人可以提供一些例子,那就太棒了。 提前致谢。

【问题讨论】:

  • 嗨,你能做到吗?如果是,请留下答案吗?

标签: python architecture microservices jwt-auth flask-restplus


【解决方案1】:

要解决这个问题,你需要制作一个装饰器token_required

装饰器token_required 的代码应该类似于:

from functools import wraps
def token_required(controller_function):
    @wraps(controller_function)
    def wrapper_function(*args, **kwargs):
        # Make endpoint in the Auth Service to validate an Auth Token
        # The endpoint will return details such as User's Account ID
        auth_token = request.headers.get('AuthToken', '')
        response = requests.get('mysite.com/validate_auth_token', headers={'AuthToken': auth_token})
        # If the Response Json has an account_id which is not empty, the user is valid
        if response.json().get('account_id'):
            controller_function(account_id, *args, **kwargs)
        else:
            # You can also redirect the user to the login page.
            abort(403, 'Invalid user')

You can also refer to this document for more information on Python Decorators

【讨论】:

    猜你喜欢
    • 2018-09-24
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 2018-07-17
    • 1970-01-01
    • 2020-09-25
    • 2014-04-09
    • 1970-01-01
    相关资源
    最近更新 更多