FastApi - api 密钥作为参数足够安全

FastApi - api key as parameter secure enough

我是这部分编程的新手,我几乎没有问题。首先是我的项目。一方面我有一个 Flutter 应用程序,另一方面我有一个带有数据的 MS SQL 服务器。从逻辑上讲,我需要在我的设备上使用这些数据。我读到最好的方法是使用 FastAPI,它简单且性能良好,但我不确定安全性。我阅读了一些关于 OAuth2 的内容,但它看起来很多,因为只有一个用户有权使用数据(服务器所有者)。是否可以只使用一个简单的 api 键作为参数?像这样...

from fastapi import FastAPI
from SqlServerRequest import SqlServerRequest

app = FastAPI()


@app.get("/openOrders/{key}")
async def openOrders(key):
    if key == "myverysecurekey":
         return "SQLDATA"
    else
         return "Wrong key"

这种方式可行,但我不确定安全性 你会怎么说?

如果您的用例只是为单个用户提供服务,而不是关键任务,这可能是一个很好的开始方式。

main.py

import os

import uvicorn
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from starlette import status

# Use token based authentication
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


# Ensure the request is authenticated
def auth_request(token: str = Depends(oauth2_scheme)) -> bool:
    authenticated = token == os.getenv("API_KEY", "DUMMY-API-KEY")
    return authenticated


app = FastAPI()


@app.get("/openOrders")
async def open_orders(authenticated: bool = Depends(auth_request)):
    # Check for authentication like so
    if not authenticated:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Not authenticated")

    # Business logic here
    return {"message": "Authentication Successful"}


if __name__ == '__main__':
    uvicorn.run("main:app", host="127.0.0.1", port=8080)

您可以 运行 使用 python main.py

然后客户端可以像这样发出请求:

import requests

url = "http://127.0.0.1:8080/openOrders"
payload={}
# The client would pass the API-KEY in the headers
headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer DUMMY-API-KEY'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)

Dart

中的客户端代码
final response = await http.get(
  Uri.parse('http://127.0.0.1:8080/openOrders'),
  // Send authorization headers to the backend.
  headers: {
    HttpHeaders.authorizationHeader: 'Bearer DUMMY-API-KEY',
  },
);