Spring Boot+Vue+Spring Security OAuth2的前后端分离项目实现研究

徒手撸springcloud+VUE--Oauth2篇 上一篇写了父工程和eureka、gateway服务的搭建和配置,基本上采用默认的配置就可完成基本的搭建,比较简单。本篇重点写点Oauth2的搭建和踩过的各种坑 一、引入相关jar包 1、oauth2的jar包和自动化配置的jar包 <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</ar 阅读详情

业余在开发一个Spring Boot+Vue+Spring Security OAuth2的一个前后端分离项目,其中遇到不少如跨域、OPTIONS请求处理、PreAuthorize注解无效、Token失效处理等问题,记录如下。

在此项目中,资源服务与授权服务在同一应用中,使用端口8081;前端应用使用端口8080。前端使用axios进行ajax调用。
关于Spring Security OAuth2相关内容,可参考:http://liumoran.cn/topic/detail?id=1

1. 后端处理跨域请求问题

如果前后端部署在不同应用服务器上,后端需要配置跨域访问才成。如未配置跨域访问,浏览器F12打开高度页面的Console界面中,可以看到以下信息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8081/getLoginUser. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

Spring Boot中配置跨域请求,可以通过定义Filter的方式实现:

@Component
public class MyCorsFilter implements Filter {
   
   
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
   
   
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-Control-Allow-Origin","http://localhost:8080");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, Authorization");
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
   
   }

    @Override
    public void destroy() {
   
   }

}

2. OPTIONS报401问题

为什么在正常的请求前要发送OPTIONS请求?

用户登录成功后,当前端往后端发送的请求中包含有Authorization头,并且是跨域请求时,浏览器将会往后端发送对应的OPTIONS请求,以确认后台服务是否支持对受保护资源的跨域访问。

由于OPTIONS请求中并不带有Token,因此请求被Spring Security OAuth2拦截到后,检查发现没有Token,直接返回401给前端页面了。

如何配置?

可以在Spring Security的配置类中配置允许所有OPTIONS请求访问,如下所示:

    @Override
    public void configure(HttpSecurity http) throws Exception {
   
   
        http
                .anonymous()
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "**").permitAll()
                .anyRequest().authenticated();
    }

其中省略掉了其它的资源访问授权配置。

但在配置后前端访问仍旧报401!!经过排查,按前面所说,我是在Spring Security的配置类中添加这个配置的,但实际上,资源服务器中对请求是否有权限访问的处理,是在资源服务器的配置中进行的,因此在单独的Spring Security配置类中进行配置并不会生效!必须在继承自ResourceServerConfigurerAdapter的配置类中进行该项配置。

在资源服务中,实际上是不需要单独的Spring Security的配置类的,直接使用ResourceServerConfigurerAdapter即可完成对各类资源的授权配置。此时的配置类如下:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfigurer extends ResourceServerConfigurerAdapter {
   
   
    @Autowired
    private RealAuthenticationProvider authenticationProvider;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
   
   
        resources.resourceId("testResource")
                .stateless(true);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
   
   
        http
                .authorizeRequests()
                    .antMatchers(HttpMethod.OPTIONS, "**").permitAll()
                    .antMatchers("/*", "/css/**/*", "/js/**/*", "/icons/**/*", "/upload/*",
                            "/h2-console/", "/h2-console/**/*", "/topic/**/*").permitAll()
                    .anyRequest().authenticated()
                .and()
                .formLogin()
                    .lo
Spring Boot+Vue/前后端分离/高并发/秒杀实战课程之spring Security快速搭建oauth2 内存版身份认证 Springboot快速搭建oauth2 内存版身份认证环境准备点击【Create New Project】创建一个新的项目项目环境配置配置Thymeleaf搭建oauth2认证,加入两个依赖包可能遇到的坑解决方案编码覆写spring Security的http配置覆写Oauth2的http配置类ResourceServerConfig.class新建一个认证服务器的类AuthorizationS... 阅读详情

相关推荐

ruoyi-vue前后端分离架构下的统一登录认证实践指南

本文详细介绍了在RuoYi-Vue前后端分离架构中实现统一登录认证(单点登录,SSO)的完整实践方案。通过解析核心流程,提供了从前端创建专用登录组件、配置路由与权限,到后端搭建安全认证桥梁、扩展登录服务及配置安全规则的具体代码实现与配置步骤,并总结了关键安全细节与优化方向,帮助企业构建高效、安全的统一认证体系。

jwt8token的博客 1184

SpringBoot 基于 OAuth2 统一身份认证流程详解

了解OAUTH2统一认证基本概念, 各种角色与协议流程, 了解OAUTH2支持的四种模式, 以及各种模式的不同应用场景。了解整体服务设计, 完成认证服务的搭建配置, 通过postman对功能进行验证, 实现TOKEN的申请与刷新功能。完成用户服务的配置的改进以及 Spring Security的集成, 核心类的处理实现;在整个项目中, 存在公用的地方, 要做统一处理, 比如统一异常和统一接口数据返回, 复用方便, 直观清晰, 便于维护与扩展。

专注基础架构领域 1万+

springBoot-springSecurity-OAuth2

springBoot整合OAuth2示例及其代码

子笙的博客 3098

三部对接 sora-2:OpenAI 最新视频模型快速接入指南

本文介绍OpenAI最新视频生成模型Sora-2的接入方案,重点解析其Chat格式调用功能。开发者可通过在提示词中嵌入"横屏/竖屏""时长""清晰度"等要求快速生成视频。文章分三部分:1)基础准备(环境配置与API密钥获取);2)核心调用(提供Python/Java示例代码);3)结果查询与优化建议。Sora-2支持多语言调用,简化了视频生成流程,适用于短视频、广告创意等场景。

2501_93565190的博客 3422

Qt5+OSG实战:如何用osgQOpenGLWidget在窗口中加载3D模型(附完整代码)

本文详细解析了如何在Qt5中使用osgQOpenGLWidget加载和渲染3D模型,涵盖环境配置、核心架构、性能优化及高级技巧。通过实战案例和完整代码,帮助开发者实现工业级3D模型渲染,提升Qt与OSG的整合效率。

weixin_42741930的博客 263

手机如何高效辅助林业调查

手机如何高效辅助林业调查 很多林业工作者将栅格类型的地形图处理后导入平板电脑,在林地使用平板电脑加载小班矢量图,辅助林业调查。但是,如果没有地形图底图,这种方法可能就有难度,而且最重要的是,大部分林地工作者没有能力配置平板电脑。大凡林业基层工作者在林地调查时,除调查记录本等部分纸质材料外,都必然携带手机和水杯,此外其他设备已经成为累赘,尤其是炎热的夏季在杂灌丛生的林地进行调查作业。因此,使用手机...

xu780820的博客 3073

unet学习笔记(milesial/Pytorch-UNet)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 unet学习笔记(milesial/Pytorch-UNet)原理讲解unet_parts.py内容predict.py内容 所用到的代码Pytorch-UNet/predict.py at master · milesial/Pytorch-UNet ·GitHub 原理讲解 蓝/白色框表示 feature map; 蓝色箭头表示 3x3 卷积,用于特征提取; 灰色箭头表示skip-connection,用于特征融合; 红色箭头.

weixin_67138138的博客 2553

Python接口自动化测试实战:Requests+Pytest+Excel+Allure框架搭建指南

接口自动化测试是现代软件工程中保障软件质量的关键实践,其核心原理是通过脚本模拟客户端请求,自动验证API的功能、性能和可靠性。在Python技术栈中,Requests库以其简洁的API成为处理HTTP请求的基石,而Pytest框架则凭借其灵活的Fixture机制和强大的参数化功能,为测试用例的组织与执行提供了优雅的解决方案。结合Excel进行数据驱动测试,能够有效实现测试数据与脚本逻辑的分离,提升协作效率;最终通过Allure生成可视化测试报告,清晰呈现测试结果与过程。这套技术组合(Requests, Py

weixin_28677451的博客 303

Python和Spyder:一个完美的编程组合

而Spyder作为一个专门为科学计算和数据分析而设计的IDE,提供了高效的开发环境和丰富的工具。无论是初学者还是专业开发者,Python和Spyder都能满足他们的需求,并为他们的工作带来便利和效率。本文将探讨Python和Spyder之间的关系,以及它们如何相互配合,提供一流的编程体验。每个工具都有其特定的优势和适用场景,开发者可以根据自己的需求选择合适的工具。而Spyder作为一个专门为科学计算而设计的IDE,提供了编写、调试和执行Python代码的环境。

CodeHeroicX的博客 1122

高通平台WIFI学习-- 基于6GHZ Discovery (STA Scanning)讲解

本文介绍了6GHz频段的网络扫描优化方案。主要内容包括:1)带内发现机制,将6GHz信道分为优先扫描信道(PSC)和非PSC信道,规范了STA发送探测请求的条件及等待时间;2)带外发现机制,通过RNR信息元素实现跨频段AP发现,减少6GHz频段干扰;3)具体扫描流程示例,包括DBS扫描和敏捷扫描的顺序安排。方案通过优化探测请求发送规则和跨频段信息共享,有效降低了信道污染和扫描延迟,日志数据验证了6GHz信道扫描的具体实现过程。

专业开发者的博客,一个从事Android WiFi和蓝牙的工程师 267

YOLOv10 的损失函数解析

YOLOv10 在 YOLO 系列的演进中进一步优化了任务解耦与动态平衡策略,通过 ​多模态损失融合、自适应样本分配 和 ​轻量化设计,显著提升了检测精度与推理效率。

浩瀚之水的专栏 1377

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

深度学习工具包 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")

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

上一篇: 【问题处理】Spring Boot中kafka消息能力不足现象及问题解决
下一篇: Spring Security OAuth专题学习-资源服务源码解读
「已注销」
博客等级 码龄19年 221粉丝 134原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值