我是编程这一部分的新手,我几乎没有什么问题。首先是我的项目。一方面,我有一个颤振应用程序,在另一边,我有一个带有数据的。我在我的设备上需要的数据是合乎逻辑的。我读到最好的方法是使用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"
那样做是可行的,但我不确定安全问题,你会怎么说?
发布于 2021-06-11 22:04:12
如果您的用例只是为单个用户服务,而不是任务关键,那么这可能是一个很好的开始。
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',
},
);
发布于 2022-07-01 13:02:52
我处理同样的问题已经有一段时间了。我需要一个简单的X键,而不是使用oauth。
您可以使用以下代码执行此操作
from fastapi import FastAPI, Depends
from fastapi.security import APIKeyHeader
import os
os.environ['API-KEY'] = '1234'.
# You would use as an environment var in real life
X_API_KEY = APIKeyHeader(name='X-API-Key')
def api_key_auth(x_api_key: str = Depends(X_API_KEY)):
""" takes the X-API-Key header and validate it with the X-API-Key in the database/environment"""
if x_api_key != os.environ['API-KEY']:
raise HTTPException(
status_code=401,
detail="Invalid API Key. Check that you are passing a 'X-API-Key' on your header."
)
app = FastAPI()
@app.get("/do_something", dependencies=[Depends(api_key_auth)])
async def do_something():
return "API is working OK."
https://stackoverflow.com/questions/67942766
复制相似问题