首页 > 解决方案 > 如何在不同的烧瓶微服务中处理身份验证

问题描述

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

我正在尝试使用 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 中。如果有人可以提供一些例子,那就太棒了。提前致谢。

标签: pythonarchitecturemicroservicesjwt-authflask-restplus

解决方案


要解决这个问题,您需要制作一个装饰器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')

您还可以参考此文档以获取有关 Python 装饰器的更多信息


推荐阅读