说明 springboot 版本 2.0.3
源码地址:点击跳转

系列

  紧接着上一篇,上一篇中登录验证都由 security 帮助我们完成了,如果我们想要增加一个验证码登录或者其它的自定义校验就没办法了,因此这一篇讲解如何实现这个功能。

一、 实现自定义登录校验类

  继承 UsernamePasswordAuthenticationFilter 类来拓展登录校验,代码如下:

public class MyUsernamePasswordAuthentication extends UsernamePasswordAuthenticationFilter{

	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
//我们可以在这里进行额外的验证,如果验证失败抛出继承AuthenticationException的自定义错误。
log.info("在这里进行验证码判断");
//只要最终的验证是账号密码形式就无需修改后续过程
return super.attemptAuthentication(request, response);
} @Override
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
// TODO Auto-generated method stub
super.setAuthenticationManager(authenticationManager);
}
}

二、 将自定义登录配置到 security 中

  编写自定义登录过滤器后,configure Bean 修改为如下:

	@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf() //跨站
.disable() //关闭跨站检测
//自定义鉴权过程,无需下面设置
.authorizeRequests()//验证策略
.antMatchers("/public/**").permitAll()//无需验证路径
.antMatchers("/user/**").permitAll()
.antMatchers("/login").permitAll()//放行登录
.antMatchers(HttpMethod.GET, "/user").hasAuthority("getAllUser")//拥有权限才可访问
.antMatchers(HttpMethod.GET, "/user").hasAnyAuthority("1","2")//拥有任一权限即可访问
//角色类似,hasRole(),hasAnyRole()
.anyRequest().authenticated()
.and()
//自定义异常处理
.exceptionHandling()
.authenticationEntryPoint(myAuthenticationEntryPoint)//未登录处理
.accessDeniedHandler(myAccessDeniedHandler)//权限不足处理
.and()
//加入自定义登录校验
.addFilterBefore(myUsernamePasswordAuthentication(),UsernamePasswordAuthenticationFilter.class)
.rememberMe()//默认放在内存中
.rememberMeServices(rememberMeServices())
.key("INTERNAL_SECRET_KEY")
// 重写usernamepasswordauthenticationFilter后,下面的formLogin()设置将失效,需要手动设置到个性化过滤器中
// .and()
// .formLogin()
// .loginPage("/public/unlogin") //未登录跳转页面,设置了authenticationentrypoint后无需设置未登录跳转页面
// .loginProcessingUrl("/public/login")//登录api
// .successForwardUrl("/success")
// .failureForwardUrl("/failed")
// .usernameParameter("id")
// .passwordParameter("password")
// .failureHandler(myAuthFailedHandle) //登录失败处理
// .successHandler(myAuthSuccessHandle)//登录成功处理
// .usernameParameter("id")
.and()
.logout()//自定义登出
.logoutUrl("/public/logout")
.logoutSuccessUrl("public/logoutSuccess")
.logoutSuccessHandler(myLogoutSuccessHandle);
}

然后再编写 Bean,代码如下:

@Bean
public MyUsernamePasswordAuthentication myUsernamePasswordAuthentication(){
MyUsernamePasswordAuthentication myUsernamePasswordAuthentication = new MyUsernamePasswordAuthentication();
myUsernamePasswordAuthentication.setAuthenticationFailureHandler(myAuthFailedHandle); //设置登录失败处理类
myUsernamePasswordAuthentication.setAuthenticationSuccessHandler(myAuthSuccessHandle);//设置登录成功处理类
myUsernamePasswordAuthentication.setFilterProcessesUrl("/public/login");
myUsernamePasswordAuthentication.setRememberMeServices(rememberMeServices()); //设置记住我
myUsernamePasswordAuthentication.setUsernameParameter("id");
myUsernamePasswordAuthentication.setPasswordParameter("password");
return myUsernamePasswordAuthentication;
}

完成。

本文原创发布于:https://www.tapme.top/blog/detail/2018-08-21-10-38

springboot+security整合(2)自定义校验的更多相关文章

  1. springboot+security整合(3)自定义鉴权

    说明 springboot 版本 2.0.3源码地址:点击跳转 系列 springboot+security 整合(1) springboot+security 整合(2) springboot+se ...

  2. springboot+security整合(1)

    说明 springboot 版本 2.0.3源码地址:点击跳转 系列 springboot+security 整合(1) springboot+security 整合(2) springboot+se ...

  3. Springboot security cas整合方案-原理篇

    前言:网络中关于Spring security整合cas的方案有很多例,对于Springboot security整合cas方案则比较少,且有些仿制下来运行也有些错误,所以博主在此篇详细的分析cas原 ...

  4. Springboot security cas整合方案-实践篇

    承接前文Springboot security cas整合方案-原理篇,请在理解原理的情况下再查看实践篇 maven环境 <dependency> <groupId>org.s ...

  5. springboot+maven整合spring security

    springboot+maven整合spring security已经做了两次了,然而还是不太熟悉,这里针对后台简单记录一下需要做哪些事情,具体的步骤怎么操作网上都有,不再赘述.1.pom.xml中添 ...

  6. Springboot学习06-Spring AOP封装接口自定义校验

    Springboot学习06-Spring AOP封装接口自定义校验 关键字 BindingResult.Spring AOP.自定义注解.自定义异常处理.ConstraintValidator 前言 ...

  7. 【全网最全】springboot整合JSR303参数校验与全局异常处理

    一.前言 我们在日常开发中,避不开的就是参数校验,有人说前端不是会在表单中进行校验的吗?在后端中,我们可以直接不管前端怎么样判断过滤,我们后端都需要进行再次判断,为了安全.因为前端很容易拜托,当测试使 ...

  8. SpringBoot 使用 JSR303 自定义校验注解

    JSR303 是 Java EE 6 中的一项子规范,叫做 Bean Validation,官方参考实现是hibernate Validator,有了它,我们可以在实体类的字段上标注不同的注解实现对数 ...

  9. Springboot security cas源码陶冶-CasAuthenticationFilter

    Springboot security cas整合方案中不可或缺的校验Filter类或者称为认证Filter类,其内部包含校验器.权限获取等,特开辟新地啃啃 继承结构 - AbstractAuthen ...

随机推荐

  1. [转]windows环境下启动与停止.jar文件

    原文地址:https://www.jianshu.com/p/b12fc379d171 1 .启动 在xx.jar同级目录下建立run.bat文件,在run.bat文件中编辑下列文本. @echo o ...

  2. (转)SQLAlchemy入门和进阶

    URL:https://zhuanlan.zhihu.com/p/27400862 https://www.cnblogs.com/mrchige/p/6389588.html---SQLAlchem ...

  3. Freemarker语法收集

    1. 取数组第一项 <#if subModelList?? && (subModelList?size > 0)> <#assign subFirst = su ...

  4. 安装tensorflow2.0

    pip install tensorflow==2.0.0 -i https://pypi.tuna.tsinghua.edu.cn/simple import tensorflow as tfpri ...

  5. nginx启动命令以及与配置systemctl

    一.配置systemctl之前的启动方式 进入sbin目录下执行以下命令: 启动nginx的命令为 /usr/local/nginx/sbin/nginx 3 停止nginx的命令为 /usr/loc ...

  6. linux:使用python脚本监控某个进程是否存在(不使用crontab)

    背景: 需要每天定时去检测crontab进程是否启动,所以不能用crontab来启动检测脚本了,直接使用while 循环和sleep方式实现定时检测 # coding:utf-8 import os ...

  7. chamfer_pcd

    import tensorflow as tf import numpy as np def distance_matrix(array1, array2): """ a ...

  8. TCP协议的11种状态及其变化过程?传输的内容又是什么?

    在TCP的11种状态变迁中,我们需要用到TCP头部的三个标志位: 1.SYN,SYN=1表示这是一个连接请求报文或者连接接受报文 2.ACK,ACK=1,表示确认号生效 3.FIN,FIN=1表示发送 ...

  9. docker使用1

    1. 安装 可以参考https://www.runoob.com/docker/centos-docker-install.html 注意linux版本是centos7.6 2. docker启动,停 ...

  10. K8S从入门到放弃系列-(16)Kubernetes集群Prometheus-operator监控部署

    Prometheus Operator不同于Prometheus,Prometheus Operator是 CoreOS 开源的一套用于管理在 Kubernetes 集群上的 Prometheus 控 ...