SpringBoot2.0.3 + SpringSecurity5.0.6 + vue 前后端分离认证授权
新项目引入安全控制
项目中新近添加了Spring Security安全组件,前期没怎么用过,加之新版本少有参考,踩坑四天,终完成初步解决方案.其实很简单,Spring Security5相比之前版本少了许多配置,操作起来更轻量
MariaDb登录配置加密策略
SpringSecurity5在执行登录认证时,需预设加密策略.
坑一:加密策略配置,验密始终不通过,报错401
坑二:本地重写的UserDetailsService实现类在注入的时候找不到,目前图省事直接用了 @Qualifier制定
其它,实体类user实现UserDetails,role实现GrantedAuthority与之前版本并有太大变动,可参考很多,不做赘述
代码如下:
/**
* 项目中重写的 UserDetailsService接口的实现类,需指定
*/
@Qualifier("userService")
@Autowired
private UserDetailsService userDetailsService;
/**
* 初始验证登录 从内存中取密码
* @param auth
* @throws Exception
*/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); }
跨域的问题
Springboot2.0.3处理跨域的时候特别简单,只需要在
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-1)
等修饰下的配置类中的HttpSecurity中,加上 cors()即可,完全不需要写过滤器包装HttpServletResponse的操作 登录报错403,权限不足
这里的解决方案很多,因为本文项目不大,直接关闭 csrf (跨站请求伪造)即可
同上,csrf().disable()即可.
最大坑--跨域打开,每次登录返回为匿名用户anonymousUser
问题描述:
跨域已打开,使用Swagger访问都没有问题,前后端分离时,SpringSecurity也正常工作,最终还是登录不成功,返回匿名用户
关闭匿名用户即 anonymous().disable(),直接报错401,用户名或密码错误
遇到这个问题,一直纠结在跨域上,却没有深入去查看前端http请求上给出的信息,原因很简单,登录时重定向的问题
在HttpSecurity中,在选择 formLogin()时,其后会选择各种成功失败的url,然后代码上去实现相关的接口,其实就入坑了.
注意:在前端使用ajax登录时,SpringSecurity只能通过重写相关成功/失败/退出等的处理器handler来完成相关处理逻辑
完整配置类代码:
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(-1)
public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler;
@Autowired
CustomizeAuthenticationFailHandler customizeAuthenticationFailHandler;
@Autowired
CustomizeAuthenticationAccessDenied customizeAuthenticationAccessDenied;
@Autowired
CustomizeAuthenticationLogout customizeAuthenticationLogout; @Override
protected void configure(HttpSecurity http) throws Exception { http
.csrf().disable()
.anonymous().disable()
.cors().and().httpBasic()
.and()
// 登录成功页面与登录失败页面
.formLogin()
.successHandler(customizeAuthenticationSuccessHandler).failureHandler(customizeAuthenticationFailHandler).permitAll().and()
// 权限不足,即403时跳转页面
.exceptionHandling().accessDeniedHandler(customizeAuthenticationAccessDenied).authenticationEntryPoint(new UnauthorizedEntryPoint())
.and().logout().logoutSuccessHandler(customizeAuthenticationLogout).permitAll().and()
.authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll()
// 无需权限 即可访问
.antMatchers("/logout").permitAll()
// 需要USER角色才可访问
.antMatchers("/person/**").hasRole("PERSON")
// 需要ADMIN角色才可访问
.antMatchers("/user/**").hasRole("ADMIN");
} /**
* 项目中重写的 UserDetailsService接口的实现类,需指定
*/
@Qualifier("userService")
@Autowired
private UserDetailsService userDetailsService;
/**
* 初始验证登录 从内存中取密码
* @param auth
* @throws Exception
*/
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); } }
重写的登录成功处理器代码如下:
@Component
public class CustomizeAuthenticationSuccessHandler implements AuthenticationSuccessHandler { private static final Logger logger = LoggerFactory.getLogger(CustomizeAuthenticationSuccessHandler.class); @Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException { logger.info("AT onAuthenticationSuccess(...) function!"); WebAuthenticationDetails details = (WebAuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
logger.info("login--IP:"+details.getRemoteAddress()); SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication1 = context.getAuthentication();
Object principal = authentication1.getPrincipal();
Object principal1 = authentication.getPrincipal(); String name = authentication.getName();
logger.info("login--name:"+name+" principal:"+principal+" principal1:"+principal1); PrintWriter out = null;
try {
out = response.getWriter();
out.append(JSONObject.toJSONString(ResponseData.ok().putDataValue("user",principal)
.putDataValue("name",name)));
} catch (IOException e){
e.printStackTrace();
}finally {
if (out != null) {
out.close();
}
}
}
}
SpringBoot2.0.3 + SpringSecurity5.0.6 + vue 前后端分离认证授权的更多相关文章
- Flask + vue 前后端分离的 二手书App
一个Flask + vue 前后端分离的 二手书App 效果展示: https://blog.csdn.net/qq_42239520/article/details/88534955 所用技术清单 ...
- SpringBoot 和Vue前后端分离入门教程(附源码)
作者:梁小生0101 juejin.im/post/5c622fb5e51d457f9f2c2381 推荐阅读(点击即可跳转阅读) 1. SpringBoot内容聚合 2. 面试题内容聚合 3. 设计 ...
- SpringBoot+Vue前后端分离,使用SpringSecurity完美处理权限问题
原文链接:https://segmentfault.com/a/1190000012879279 当前后端分离时,权限问题的处理也和我们传统的处理方式有一点差异.笔者前几天刚好在负责一个项目的权限管理 ...
- Springboot+vue前后端分离项目,poi导出excel提供用户下载的解决方案
因为我们做的是前后端分离项目 无法采用response.write直接将文件流写出 我们采用阿里云oss 进行保存 再返回的结果对象里面保存我们的文件地址 废话不多说,上代码 Springboot 第 ...
- 解决Django+Vue前后端分离的跨域问题及关闭csrf验证
前后端分离难免要接触到跨域问题,跨域的相关知识请参:跨域问题,解决之道 在Django和Vue前后端分离的时候也会遇到跨域的问题,因为刚刚接触Django还不太了解,今天花了好长的时间,查阅了 ...
- 喜大普奔,两个开源的 Spring Boot + Vue 前后端分离项目可以在线体验了
折腾了一周的域名备案昨天终于搞定了. 松哥第一时间想到赶紧把微人事和 V 部落部署上去,我知道很多小伙伴已经等不及了. 1. 也曾经上过线 其实这两个项目当时刚做好的时候,我就把它们部署到服务器上了, ...
- 两个开源的 Spring Boot + Vue 前后端分离项目
折腾了一周的域名备案昨天终于搞定了. 松哥第一时间想到赶紧把微人事和 V 部落部署上去,我知道很多小伙伴已经等不及了. 1. 也曾经上过线 其实这两个项目当时刚做好的时候,我就把它们部署到服务器上了, ...
- beego-vue URL重定向(beego和vue前后端分离开发,beego承载vue前端分离页面部署)
具体过程就不说,是搞这个的自然会动,只把关键代码贴出来. beego和vue前后端分离开发,beego承载vue前端分离页面部署 // landv.cnblogs.com //没有授权转载我的内容,再 ...
- Jeecg-Boot 2.0 版本发布,基于Springboot+Vue 前后端分离快速开发平台
目录 Jeecg-Boot项目简介 源码下载 升级日志 Issues解决 v1.1升级到v2.0不兼容地方 系统截图 Jeecg-Boot项目简介 Jeecg-boot 是一款基于代码生成器的智能开发 ...
随机推荐
- JVM-Java内存区域
JVM虚拟机运行时数据区结构分为: 其中方法区和堆是所有线程共享的内存区域,而Java栈.本地方法栈.程序计数器是线程私有的. 我们详细介绍运行时数据区的各个区域及其作用. 程序计数器: 一块较小的内 ...
- 如何添加一种新Case协议
这里以添加基础http为例 首先要在脚本文件(XML文件)中定义好这种协议的基本信息 您必须在这里设计好您协议预先需要的数据(比如串口协议,那波特率,串口号等可能是不会经常改变的就可以在这里先 ...
- Redux与它的中间件:redux-thunk,redux-actions,redux-promise,redux-saga
序言 这里要讲的就是一个Redux在React中的应用问题,讲一讲Redux,react-redux,redux-thunk,redux-actions,redux-promise,redux-sag ...
- JAVA验证身份证格式及合法性
旅游电子商务中,预订酒店或订购门票时会以身份证作为消费凭证,为了防止客户误填身份证带来不必要麻烦,需要验证码格式及合法性,代码如下: /** * 判断身份证格式 * * @param idNum * ...
- python实现本地图片上传到服务区
本地图片上传到服务器,其本质上来讲,就是读取本地图片,复制到服务器,并返回服务器url 前端代码,用的form表单提交,form表单中包含两个文件选择表单元素,选择文件,点击提交按钮,提交form表单 ...
- Python—time模块介绍
time 模块 在平常的代码中,我们常常需要与时间打交道.在Python中,常用的与时间处理有关的模块就包括:time,datetime,下面来介绍time模块. 在开始之前,首先要说明几点: 一.在 ...
- C. Prefixes and Suffixes
链接 [https://codeforces.com/contest/1092/problem/C] 题意 给你某个字符串的长度n,再给你2*n-2个前缀或者后缀 让你判断那些是前缀那些是后缀 关键是 ...
- 【RSYSLOG】The Property Replacer【转】
最近在调整日志平台的日志格式,一下是RSYSLOG的 Property Replacer 说明.鉴于RSYSLOG官网略坑,转发一下,原地址忘记了- - ||| The property replac ...
- hibernate添加数据时Exception in thread "main" org.hibernate.PropertyValueException: not-null property references a null or transient value: com.javakc.hibernate.test.entity.TestEntity.testName
意思是,一个非null属性引用了一个null或瞬态值.就是在对应实体类配置文件hbm.xml中该属性配置了not-null="true",将其去掉即可.
- scrapy之管道
scrapy之管道 通过管道将数据持久化到数据库中,企业中常见的数据库是MySQL,分布式爬取数据时只能讲数据存储到Redis装,还可以将数据存储到本地磁盘(即写入到本地文件中). 未完待续... 0