SpringSecurity学习之自定义过滤器
我们系统中的认证场景通常比较复杂,比如说用户被锁定无法登录,限制登录IP等。而SpringSecuriy最基本的是基于用户与密码的形式进行认证,由此可知它的一套验证规范根本无法满足业务需要,因此扩展势在必行。那么我们可以考虑自己定义filter添加至SpringSecurity的过滤器栈当中,来实现我们自己的验证需要。
本例中,基于前篇的数据库的Student表来模拟一个简单的例子:当Student的jointime在当天之后,那么才允许登录
一、创建自己定义的Filter
我们先在web包下创建好几个包并定义如下几个类

CustomerAuthFilter:
package com.bdqn.lyrk.security.study.web.filter; import com.bdqn.lyrk.security.study.web.authentication.UserJoinTimeAuthentication;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; public class CustomerAuthFilter extends AbstractAuthenticationProcessingFilter { private AuthenticationManager authenticationManager; public CustomerAuthFilter(AuthenticationManager authenticationManager) { super(new AntPathRequestMatcher("/login", "POST"));
this.authenticationManager = authenticationManager; } @Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
String username = request.getParameter("username");
UserJoinTimeAuthentication usernamePasswordAuthenticationToken =new UserJoinTimeAuthentication(username);
Authentication authentication = this.authenticationManager.authenticate(usernamePasswordAuthenticationToken);
if (authentication != null) {
super.setContinueChainBeforeSuccessfulAuthentication(true);
}
return authentication;
}
}
该类继承AbstractAuthenticationProcessingFilter,这个filter的作用是对最基本的用户验证的处理,我们必须重写attemptAuthentication方法。Authentication接口表示授权接口,通常情况下业务认证通过时会返回一个这个对象。super.setContinueChainBeforeSuccessfulAuthentication(true) 设置成true的话,会交给其他过滤器处理。
二、定义UserJoinTimeAuthentication
package com.bdqn.lyrk.security.study.web.authentication;
import org.springframework.security.authentication.AbstractAuthenticationToken;
public class UserJoinTimeAuthentication extends AbstractAuthenticationToken {
private String username;
public UserJoinTimeAuthentication(String username) {
super(null);
this.username = username;
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getPrincipal() {
return username;
}
}
自定义授权方式,在这里接收username的值处理,其中getPrincipal我们可以用来存放登录名,getCredentials可以存放密码,这些方法来自于Authentication接口
三、定义AuthenticationProvider
package com.bdqn.lyrk.security.study.web.authentication; import com.bdqn.lyrk.security.study.app.pojo.Student;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import java.util.Date; /**
* 基本的验证方式
*
* @author chen.nie
* @date 2018/6/12
**/
public class UserJoinTimeAuthenticationProvider implements AuthenticationProvider {
private UserDetailsService userDetailsService; public UserJoinTimeAuthenticationProvider(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
} /**
* 认证授权,如果jointime在当前时间之后则认证通过
* @param authentication
* @return
* @throws AuthenticationException
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = (String) authentication.getPrincipal();
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
if (!(userDetails instanceof Student)) {
return null;
}
Student student = (Student) userDetails;
if (student.getJoinTime().after(new Date()))
return new UserJoinTimeAuthentication(username);
return null;
} /**
* 只处理UserJoinTimeAuthentication的认证
* @param authentication
* @return
*/
@Override
public boolean supports(Class<?> authentication) {
return authentication.getName().equals(UserJoinTimeAuthentication.class.getName());
}
}
AuthenticationManager会委托AuthenticationProvider进行授权处理,在这里我们需要重写support方法,该方法定义Provider支持的授权对象,那么在这里我们是对UserJoinTimeAuthentication处理。
四、WebSecurityConfig
package com.bdqn.lyrk.security.study.app.config; import com.bdqn.lyrk.security.study.app.service.UserService;
import com.bdqn.lyrk.security.study.web.authentication.UserJoinTimeAuthenticationProvider;
import com.bdqn.lyrk.security.study.web.filter.CustomerAuthFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /**
* spring-security的相关配置
*
* @author chen.nie
* @date 2018/6/7
**/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired
private UserService userService; @Override
protected void configure(HttpSecurity http) throws Exception {
/*
1.配置静态资源不进行授权验证
2.登录地址及跳转过后的成功页不需要验证
3.其余均进行授权验证
*/
http.
authorizeRequests().antMatchers("/static/**").permitAll().
and().authorizeRequests().antMatchers("/user/**").hasRole("7022").
and().authorizeRequests().anyRequest().authenticated().
and().formLogin().loginPage("/login").successForwardUrl("/toIndex").permitAll()
.and().logout().logoutUrl("/logout").invalidateHttpSession(true).deleteCookies().permitAll()
; http.addFilterBefore(new CustomerAuthFilter(authenticationManager()), UsernamePasswordAuthenticationFilter.class); } @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//设置自定义userService
auth.userDetailsService(userService);
auth.authenticationProvider(new UserJoinTimeAuthenticationProvider(userService));
} @Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
}
在这里面我们通过HttpSecurity的方法来添加我们自定义的filter,一定要注意先后顺序。在AuthenticationManagerBuilder当中还需要添加我们刚才定义的 AuthenticationProvider
启动成功后,我们将Student表里的jointime值改为早于今天的时间,进行登录可以发现:

SpringSecurity学习之自定义过滤器的更多相关文章
- angularjs学习第三天笔记(过滤器第二篇---filter过滤器及其自定义过滤器)
您好,我是一名后端开发工程师,由于工作需要,现在系统的从0开始学习前端js框架之angular,每天把学习的一些心得分享出来,如果有什么说的不对的地方,请多多指正,多多包涵我这个前端菜鸟,欢迎大家的点 ...
- vue.js学习 自定义过滤器使用(1)
在这个教程中,我们将会通过几个例子,了解和学习VueJs的过滤器.我们参考了一些比较完善的过滤器,比如orderBy 和 filterBy.而且我们可以链式调用过滤器,一个接一个过滤.因此,我们可以定 ...
- Vue.js学习 Item14 – 过滤器与自定义过滤器
基础 类似于自定义指令,可以用全局方法 Vue.filter() 注册一个自定义过滤器,它接收两个参数:过滤器 ID 和过滤器函数.过滤器函数以值为参数,返回转换后的值: Vue.filter('re ...
- vue.js学习 自定义过滤器使用(2)
gitHub地址: https://github.com/lily1010/vue_learn/tree/master/lesson05 一 自定义过滤器(注册在Vue全局) 注意事项: (1)全局方 ...
- SpringCloud学习笔记(19)----Spring Cloud Netflix之服务网关Zuul自定义过滤器
zuul不仅只是路由,还可以自定义过滤器来实现服务验证. 实现案例:自定义过滤器,检验头部是否带有token,如果token=wangx,则通过校验,若不存在或不为wangx则返回提示token错误. ...
- Spring Cloud Alibaba学习笔记(19) - Spring Cloud Gateway 自定义过滤器工厂
在前文中,我们介绍了Spring Cloud Gateway内置了一系列的内置过滤器工厂,若Spring Cloud Gateway内置的过滤器工厂无法满足我们的业务需求,那么此时就需要自定义自己的过 ...
- 小白学习django第三站-自定义过滤器及标签
要使用自定义过滤器和标签,首先要设置好目录结构 现在项目目录下建立common的python包 再将common加入到setting.py中的INSTALLED_APP列表中 在common创建目录t ...
- Spring-Security (学习记录四)--配置权限过滤器,采用数据库方式获取权限
目录 1. 需要在spring-security.xml中配置验证过滤器,来取代spring-security.xml的默认过滤器 2. 配置securityMetadataSource,可以通过ur ...
- Django学习——Django settings 源码、模板语法之传值、模板语法之获取值、模板语法之过滤器、模板语法之标签、自定义过滤器、标签、inclusion_tag、模板的导入、模板的继承
Django settings 源码 """ 1.django其实有两个配置文件 一个是暴露给用户可以自定义的配置文件 项目根目录下的settings.py 一个是项目默 ...
随机推荐
- LRU ,LRUW,CKPT-Q
原文出处:http://www.itpub.net/thread-1631537-1-1.html http://www.linuxidc.com/Linux/2012-07/66767.htm ...
- 《SQL必知必会》笔记
SQL必知必会(第4版) 作者:[美]Ben Forta 本书介绍了sql在不同数据库工具(Oracle.SQLite.SQL server.MySQL.MariaDB.PostgreSQL...)是 ...
- 《mysql必知必会》学习_第三章_20180724_欢
P16: use crashcourse; #选择数据库#使用crashcouse这个数据库,因为我没有crashcourse这个数据库,所以用我的hh数据库代替. P17: show databas ...
- 分类算法之朴素贝叶斯分类(Naive Bayesian classification)
1.1.摘要 贝叶斯分类是一类分类算法的总称,这类算法均以贝叶斯定理为基础,故统称为贝叶斯分类.本文作为分类算法的第一篇,将首先介绍分类问题,对分类问题进行一个正式的定义.然后,介绍贝叶斯分类算法的基 ...
- js-设置时间,获取几天后的时间
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8&qu ...
- ASP.NET Web API 框架研究 Action的选择
如何从HttpController众多方法里如何选择出有效的Action方法?主要分一下几个步骤: 首先,获取候选HttpActionDescriptor列表(ILookup(string,HttpA ...
- C# 使用Queue<T>代替递归算法遍历树
递归时候每次调用自身在堆栈上要记录返回地址,而堆栈的空间很少,调用次数多了后会产生堆栈溢出,以下代码是实际项目中,通过Queue<T>来避免递归算法的代码: /// <summary ...
- unigui1404在delphi10.2.2安装
unigui1404在delphi10.2.2安装 UNIGUI1404不能直接在DELPHI10.2.2下面编译安装,在10.2.1下面是可以的. 这里讲下怎样安装的方法: 1)执行FMSoft_u ...
- IDHTTP的基本用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 3 ...
- 停止一个java的线程执行
找了一个停止线程运行的方法,代码如下: public class stopThread extends Thread { private volatile boolean stop = false; ...