说明 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. grandle Project sync failed.please fix your project and try again

    Android Studio导入项目或者新建项目想运行的时候可能会报错Gradle project sync failed. Please fix your project and try again ...

  2. (转)CentOS 7.6 上编译安装httpd 2.4.38

    原文:https://www.s4lm0x.com/archives/40.html https://www.cnblogs.com/sunshine-H/p/8110608.html----超详细 ...

  3. sqlserver表被锁了,解锁方法,删除锁的方法

    -- 查询死锁select        request_session_id spid,       OBJECT_NAME(resource_associated_entity_id) table ...

  4. dataTable.NET的search box每輸入一個字母進行一次檢索的問題

    當使用dataTable.NET時,可以通到簡單的setting來添加一個search box進行全表格的檢索. $('#test-listing') .on('order.dt', function ...

  5. [LeetCode] 655. Print Binary Tree 打印二叉树

    Print a binary tree in an m*n 2D string array following these rules: The row number m should be equa ...

  6. 【C/C++开发】C++编译指令#pragma pack的配对使用

    C++编译指令#pragma pack的配对使用 #pragma pack可以用来指定C++数据结构的成员变量的内存对齐数值(可选值为1,2,4,8,16). 本文主要是强调在你的头文件中使用pack ...

  7. 查看Linux是CentOS还是Ubuntu

    lsb_release -a

  8. Qt信号-槽原理剖析--(2)自己实现信号槽

    时间乃是最大的革新家--培根 先了解一下相关宏: qt为c++增加的相关宏:signals, slots,emit 在qt的预编译过程中,这些宏会被替换. 1)#define signals publ ...

  9. kafka示例

    1. 引入依赖 <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-c ...

  10. ubuntu sh脚本激活conda 虚拟环境

    第一步:初始化coda 命令:sudo gedit ~/.bashrc 第二部:复制其中这样一段代码 # >>> conda initialize >>> # !! ...