17、FastAPI 中的认证、安全与 WebSocket 双向通信

FastAPI 中的认证、安全与 WebSocket 双向通信

1. FastAPI 中的认证与安全

在 Web 开发中,跨域资源共享(CORS)和跨站请求伪造(CSRF)是两个重要的安全问题。在 FastAPI 中,我们可以通过一些配置和技术来解决这些问题。

1.1 CORS 与简单请求

在浏览器规则中,有两种“简单请求”不需要预检请求。而当启用 JSON 内容类型时,在 GET 和 POST 请求之前会执行 OPTIONS 请求,即预检请求。通过适当的配置,我们可以在前端应用和不同源的后端之间进行跨域 HTTP 请求。不过,这并不能直接提升应用的安全性,但能让特定场景正常工作,同时保证对其他网络的安全性。

然而,这些策略并不能完全消除 CSRF 风险。“简单请求”仍然存在问题,例如 POST 请求会被允许执行,即使响应无法被读取,但实际上服务器已经执行了该请求。

1.2 双提交 cookie 防止 CSRF 攻击

当依赖 cookie 存储用户凭证时,我们容易受到 CSRF 攻击,因为浏览器会自动将 cookie 发送到服务器。特别是对于浏览器认为的“简单请求”,在请求执行前不会强制执行 CORS 策略。此外,传统 HTML 表单提交或图像标签的 src 属性也可能存在攻击向量。

为了减轻这种风险,我们需要额外的安全层。以下是具体的操作步骤:
1. 安装依赖库 :
为了实现双提交 cookie 模式,我们需要安装 starlette-csrf 库,运行以下命令:
bash (ve

相关推荐

FastAPI实时通信:WebSocket 构建实时推送与聊天室应用详解

本文介绍了如何使用FastAPI构建实时通信应用。首先通过WebSocket协议创建基础的双向通信端点,实现消息回显功能;然后进阶开发多用户聊天室,通过连接管理器维护活跃连接并实现消息广播;接着探讨生产环境中的安全认证方案;最后针对水平扩展需求提出基于Redis Pub/Sub的解决方案。文章对比了HTTP与WebSocket的特性差异,完整展示了从零开发到生产部署的实时应用构建流程。(149字)

数据知道的博客 1225

抖音小游戏(IAA)巨量引擎投放指南

摘要:本文详细介绍了在巨量引擎平台投放小游戏广告的完整流程,包括五个关键步骤:1)添加小游戏资产,填写ID等信息并等待审核;2)添加事件管理,配置激活和关键行为事件;3)通过橙子建站创建落地页,设置跳转链接;4)新建广告项目,选择小程序推广目标;5)完成广告创建。

分享前端工程化、AI 应用、Agent 开发与大模型实践! 4481

Win10/Win11系统下,用VSCode编译Betaflight固件最全避坑指南(从GCC安装到HEX生成)

本文详细介绍了在Win10/Win11系统下使用VSCode编译Betaflight固件的完整流程,包括GCC安装、环境变量配置、终端选择、Make工具安装等关键步骤,帮助开发者避开常见陷阱,高效生成HEX文件。特别针对VSCode环境优化和编译错误排查提供了实用解决方案。

weixin_42557803的博客 415

经典点云配准算法:迭代最近点算法ICP(Iterative Closest Point)

迭代最近点算法,又名为 ICP(Iterative Closest Point)算法。 (1)ICP算法对初始值的依赖比较大,具体的配准过程中,如何选择初始值是一个问题,可以使用轮式里程计、imu预积分或其它先验的配准结果。 (2)ICP迭代次数过多,实际工程中需要考虑到其实时性的优化问题。 (3)迭代终止的阀值的设置也是需要考虑的点,可以考虑自适应阀值的方法。 (4)关于寻找最近点可以使用kdtree进行临近搜索。

qq_35102059的博客 1万+

UNet改进(19):基于残差注意力模块Residual Attention的高效分割网络设计

本文提出一种结合注意力机制的改进UNet网络,通过引入残差注意力模块(ResidualAttentionBlock)增强医学图像分割性能。该网络在传统UNet的U型结构基础上,创新性地将轻量级注意力机制与残差连接相结合,在编码器-解码器各层级实现特征重标定。改进后的网络具有三方面优势:通过注意力机制自适应聚焦关键特征区域,利用残差连接缓解梯度消失问题,采用模块化设计灵活配置注意力位置。

2501_91516851的博客 780

RAGFlow 系列教程 第三课:后端服务入口与请求生命周期

本文深入解析RAGFlow v0.25.0后端核心机制,重点介绍了Quart框架选型原因和服务启动流程。RAGFlow选择Quart作为Web框架,主要基于其异步能力对LLM调用的支持、Flask生态兼容性以及长响应超时处理优势。文章详细拆解了服务启动的8个关键步骤,从日志初始化到HTTP服务启动,并分析了配置加载、数据库初始化等核心环节。通过源码分析揭示了RAGFlow如何实现动态API注册、双重认证体系等关键技术点,为深入理解该系统的请求处理生命周期提供了基础。

weixin_43674738的博客 187

Windows VHD的新玩法——设置任意挂载点

vhd 挂载隐藏的虚拟分区 详细过程 分别使用CreateVirtualDisk和OpenVirtalDisk来创建和打开虚拟磁盘文件。 使用AttachVirtualDisk,必须具有管理员权限才能成功执行此步骤。 初始化设备(延时Sleep),获取附加 VHD 的 UNC 路径:\\.\PhysicalDrive# 。 使用FindFirstVolume/FindNextVolume枚举已安装的卷以查找虚拟磁盘上的卷。 使用SetVolumeMountPoint将卷挂载到文件夹或者设

圣三一 2583

海康VisionMaster与西门子PLC1200进行S7通信

通信是连通算法平台和外部设备的重要渠道,在海康VisionMaster算法平台中既支持外部数据的读入也支持数据的写出,当通信构建起来以后既可以把软件处理结果发送给外界,又可以通过外界发送字符来触发相机拍照或者软件运行。 本文以西门子PLC1200作为外部设备为例,讲解海康VisionMaster与西门子PLC1200进行S7通信。......

haier123888的博客 1万+

MOS五类漏电流与优化策略

分析了五种主要漏电流机制:1)反偏结泄漏,由PN结热激发和隧

硬核科技 442

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

上一篇: 22、冰岛自由流动权利与居住登记制度解析
下一篇: 2、量子计算基础入门
dapp9builder
博客等级 码龄1天 0粉丝 1648原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值