FastAPI 使用JWT认证的中间件 fastapi的中间件还是太少,单独开发JWT需要,starlette本身提供认证相关实现,只需要自定义一个AuthenticationBackend即可,本次我们实现使用中间价方式拆包JWT的令牌,获取payload里面的用户信息 私有定义的payload内容格式如下 { “usid”: “SkDQBhEjUfygRSeEBech”, //UUID Short “uname”: “test user name”, //Username “mid”:”700010001″ // Member ID } 调用代码 app = FastAPI() app.add_middleware(AuthenticationMiddleware,backend=JWTAuthenticationBackend(secret_key=”YOUR_SECRET_KEY”)) 完整的代码 import jwt from starlette.authentication import ( AuthenticationBackend, AuthenticationError, BaseUser, AuthCredentials, UnauthenticatedUser ) class JWTUser(BaseUser): def __init__(self, user_id_short: str, member_number: str, user_name: str,token: str, payload: dict) -> None: self.user_name = user_name …
Monthly Archives: May 2020
Docker中使用conda不能激活环境问题
Anaconda或者miniconda在容器中安装以后,需要手动执行一下 conda init以后才可以激活相应的环境 假设conda的安装目录prefix为 /opt/conda/ 查看init以后的~/.bashrc,发现conda是根据shell的类型执行相应的安装 __conda_setup=”$(‘/opt/conda/bin/conda’ ‘shell.bash’ ‘hook’ 2> /dev/null)” if [ $? -eq 0 ]; then eval “$__conda_setup” else if [ -f “/opt/conda/etc/profile.d/conda.sh” ]; then . “/opt/conda/etc/profile.d/conda.sh” else export PATH=”/opt/conda/bin:$PATH” fi fi unset __conda_setup 安装完成conda以后,直接执行相同的操作,启动/bin/bash时默认就会激活base环境 Ln -s /opt/conda/etc/profile.d/conda.sh /etc/profile.d/conda.sh echo “. /opt/conda/etc/profile.d/conda.sh” >> ~/.bashrc # echo “conda activate base” >> ~/.bashrc export PATH=”/opt/conda/bin:$PATH” …