java怎样实现自定义过滤关键词_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值改为早于今天的时间,进行登录可以发现:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
java怎样实现自定义过滤关键词_SpringSecurity学习之自定义过滤器的实现代码相关推荐
- Java Web--HTML、CSS、JavaScript详细学习笔记(内含丰富示例代码)
** Java Web–HTML.CSS.JavaScript学习笔记 ** HTML(Hyper Text Markup Language超文本标记语言):控制的是页面的内容,是由标签组成的语言,能 ...
- scrapy中自定义过滤规则以及start_urls不进过滤器的问题
为什么要自定义过滤规则呢? 首先,我们需要过滤,但是不是说抓一次就不抓了,因为我们的抓取是一段时间抓取一次 自定义策略如下: 首先我试图直接继承RFPDupeFilter 在settings.py同级 ...
- 自定义request_ASP.NET Core 学习之自定义异常处理
(给DotNet加星标,提升.Net技能) 转自:#山鸡 cnblogs.com/ShenNan/p/10197231.html 为什么异常处理选择中间件? 传统的ASP.NET可以采用异常过滤器的方 ...
- Java虚拟机JVM学习06 自定义类加载器 父委托机制和命名空间的再讨论
Java虚拟机JVM学习06 自定义类加载器 父委托机制和命名空间的再讨论 创建用户自定义的类加载器 要创建用户自定义的类加载器,只需要扩展java.lang.ClassLoader类,然后覆盖它的f ...
- java防XSS攻击的 关键词过滤实现
继承HttpServletRequestWrapper,实现对请求参数的过滤/*** xss请求适配器*/ public class XssHttpServletRequestWrapper exte ...
- Pig自定义过滤UDF和加载UDF
Pig是一种数据流编程语言,由一系列操作和变换构成,每一个操作或者变换都对输入进行处理,然后产生输出结果,整体操作表示一个数据流.Pig的执行环境将数据流翻译为可执行的内部表示,在Pig内部,这些变换 ...
- 我的Java教程,不断整理,反复学习,记录着那些年大学奋斗的青春
@Author:Runsen @Date:2020/5/31 人生最重要的不是所站的位置,而是内心所朝的方向.只要我在每篇博文中写得自己体会,修炼身心:在每天的不断重复学习中,耐住寂寞,练就真功,不畏 ...
- javaweb学习6——自定义标签
声明:本文只是自学过程中,记录自己不会的知识点的摘要,如果想详细学习JavaWeb,请到孤傲苍狼博客学习,JavaWeb学习点此跳转 本文链接:https://www.cnblogs.com/xdp- ...
- 《Java Web开发入门很简单》学习笔记
<Java Web开发入门很简单>学习笔记 1123 第1章 了解Java Web开发领域 Java Web主要涉及技术包括:HTML.JavaScript.CSS.JSP.Servlet ...
最新文章
- java 手编线程池_死磕 java线程系列之自己动手写一个线程池
- ARM研发进展与企业清单
- 简单的图片处理servlet
- Enable Authentication on MongoDB
- 将JavaFX 2.0与Swing和SWT集成
- 自学Python6个月,找到了月薪8K的工作,多亏了这套学习方式
- 做DNS子域委派配置
- 李晓枫:金融信息化发展和创新的三方面
- iOS开发之Undefined symbols for architecture x86_64报错
- 2017程序员综合素质调研测试
- web-jsp(15) 购物车
- 2021中青杯数学建模A题
- Ant Design - Anchor
- 如何将OnlyOffice与NextCloud集成
- < mapreduce >论文学习笔记
- oracle mrp/rfs进程,挑战dataguard(3)——dataguard相关进程(RFS,LNSn,MRP,LSP)和参数配置...
- 【数据可视化】十八年纵观十大编程语言之争,Java和C语言的榜首之战。
- [Python 爬虫之路3] 使用seletom,爬取淘女郎-美人库的内容
- python中特殊字符输出
- switch语句及三种循环语句
热门文章
- [网络安全提高篇] 一〇八.Powershell和PowerSploit脚本渗透详解 (1)
- [Python爬虫] scrapy爬虫系列 一.安装及入门介绍
- iOS之深入解析通知NSNotification的底层原理
- OpenGL之深入解析渲染架构和数据传递
- 126. Word Ladder II
- PaddlePaddle训练营——公开课——AI核心技术掌握——第2章机器能“看”的现代技术——源自视觉神经原理的卷积网络简介及深入理解
- 大数据WEB阶段Spring框架 AOP面向切面编程(一)
- Linux(五) 权限
- js reduce实现中间件_实现redux中间件-洋葱模型
- python列表求平均值_python与统计概率思维