SpringSecurity自定义AuthenticationProvider和AuthenticationFilter
AuthenticationProvider
- 默认实现:DaoAuthenticationProvider
授权方式提供者,判断授权有效性,用户有效性,在判断用户是否有效性,它依赖于UserDetailsService实例,开发人员可以自定义UserDetailsService的实现。
- additionalAuthenticationChecks方法校验密码有效性
- retrieveUser方法根据用户名获取用户
- createSuccessAuthentication完成授权持久化
@Component
@Slf4j
public class LindAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
@Autowired
UserDetailsService userDetailsService;
@Autowired
private PasswordEncoder passwordEncoder;
/**
* 校验密码有效性.
*
* @param userDetails .
* @param authentication .
* @throws AuthenticationException .
*/
@Override
protected void additionalAuthenticationChecks(
UserDetails userDetails, UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
if (authentication.getCredentials() == null) {
logger.debug("Authentication failed: no credentials provided");
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
String presentedPassword = authentication.getCredentials().toString();
if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
logger.debug("Authentication failed: password does not match stored value");
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
}
/**
* 获取用户.
*
* @param username .
* @param authentication .
* @return
* @throws AuthenticationException .
*/
@Override
protected UserDetails retrieveUser(
String username, UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
UserDetails loadedUser = userDetailsService.loadUserByUsername(username);
if (loadedUser == null) {
throw new InternalAuthenticationServiceException(
"UserDetailsService returned null, which is an interface contract violation");
}
return loadedUser;
}
}
/**
* 授权持久化.
*/
@Override
protected Authentication createSuccessAuthentication(Object principal,
Authentication authentication, UserDetails user) {
return super.createSuccessAuthentication(principal, authentication, user);
}
AuthenticationFilter
- 默认实现:UsernamePasswordAuthenticationFilter
授权过滤器,你可以自定义它,并把它添加到默认过滤器前或者后去执行,主要用来到授权的持久化,它可以从请求上下文中获取你的user,password等信息,然后去判断它是否符合规则,最后通过authenticate方法去授权。默认的UsernamePasswordAuthenticationFilter
过滤器,主要判断请求方式是否为post,并且对username和password进行了默认值的处理,总之,在这个过滤器里不会涉及到具体业务。
public class LindUserNameAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public LindUserNameAuthenticationFilter() {
super(new AntPathRequestMatcher("/login", "GET"));
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username == null) {
throw new InternalAuthenticationServiceException("Failed to get the username");
}
if (password == null) {
throw new InternalAuthenticationServiceException("Failed to get the password");
}
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
username, password);
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
return this.getAuthenticationManager().authenticate(authRequest);
}
}
UserDetialsService
这是一个接口,有默认的实现方式,一般的,我们需要根据业务去重新实现它,比如从你的用户表获取当前授权的用户信息,你需要在UserDetialsService实现类里对用户表进行读取操作;它一般会在AuthenticationProvider里的retrieveUser方法中被使用,这就像面向对象里的模板方法模式一样,springSecurity把检验的步骤设计好了,咱们开发只要根据规则去实现具体细节就好。
@Component
public class MyUserDetailService implements UserDetailsService {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
/*
设置用户和角色需要注意:
1. commaSeparatedStringToAuthorityList放入角色时需要加前缀ROLE_,而在controller使用时不需要加ROLE_前缀
2. 放入的是权限时,不能加ROLE_前缀,hasAuthority与放入的权限名称对应即可
*/
List<UserDetails> userDetailsList = new ArrayList<>();
userDetailsList.add(User.builder()
.username("admin")
.password(passwordEncoder.encode("123"))
.authorities(AuthorityUtils.commaSeparatedStringToAuthorityList("read,ROLE_ADMIN")).build());
userDetailsList.add(User.builder()
.username("user")
.password(passwordEncoder.encode("123"))
.authorities(AuthorityUtils.commaSeparatedStringToAuthorityList("read,ROLE_USER"))
.build());
//获取用户
return userDetailsList.stream()
.filter(o -> o.getUsername().equals(name))
.findFirst()
.orElse(null);
}
}
在WebSecurityConfig里开启它
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
LindAuthenticationSuccessHandler lindAuthenticationSuccessHandler;
@Autowired
LindAuthenticationFailHandler lindAuthenticationFailHandler;
@Autowired
LindAuthenticationProvider lindAuthenticationProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/index").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")//按路由授权
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/hello")//默认登录成功后跳转的页面
.successHandler(lindAuthenticationSuccessHandler)
.failureHandler(lindAuthenticationFailHandler)
.permitAll()
.and()
.addFilterAt(lindAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class).authorizeRequests().and()
.logout()
.permitAll();
}
/**
* 自定义的Filter.
*/
@Bean
LindUserNameAuthenticationFilter lindAuthenticationFilter() {
LindUserNameAuthenticationFilter phoneAuthenticationFilter = new LindUserNameAuthenticationFilter();
ProviderManager providerManager =
new ProviderManager(Collections.singletonList(lindAuthenticationProvider));
phoneAuthenticationFilter.setAuthenticationManager(providerManager);
phoneAuthenticationFilter.setAuthenticationSuccessHandler(lindAuthenticationSuccessHandler);
phoneAuthenticationFilter.setAuthenticationFailureHandler(lindAuthenticationFailHandler);
return phoneAuthenticationFilter;
}
/**
* 密码生成策略.
*
* @return
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
认证时执行的顺序
- LindUserNameAuthenticationFilter
- LindAuthenticationProvider.retrieveUser
- LindAuthenticationProvider.additionalAuthenticationChecks
- UserDetailsService
- Authentication
springSecurity源码:https://github.com/spring-projects/spring-security
SpringSecurity自定义AuthenticationProvider和AuthenticationFilter的更多相关文章
- SpringSecurity 自定义用户 角色 资源权限控制
SpringSecurity 自定义用户 角色 资源权限控制 package com.joyen.learning.security; import java.sql.ResultSet; impor ...
- SpringSecurity 自定义表单登录
SpringSecurity 自定义表单登录 本篇主要讲解 在SpringSecurity中 如何 自定义表单登录 , SpringSecurity默认提供了一个表单登录,但是实际项目里肯定无法使用的 ...
- SpringSecurity自定义登陆页面和跳转页面
如果我们不用form-login说明登陆界面,springsecurity框架将自动为我们生成登陆界面 现在我们不想用自动生成的登陆界面了,而想使用自定义的漂亮的登陆界面 则需要使用<secur ...
- springSecurity自定义认证配置
上一篇讲了springSecurity的简单入门的小demo,认证用户是在xml中写死的.今天来说一下自定义认证,读取数据库来实现认证.当然,也是非常简单的,因为仅仅是读取数据库,权限是写死的,因为相 ...
- SpringSecurity自定义过滤器
applicationContext-security.xml: <beans:beans xmlns="http://www.springframework.org/schema/s ...
- Spring-Security 自定义Filter完成验证码校验
Spring-Security的功能主要是由一堆Filter构成过滤器链来实现,每个Filter都会完成自己的一部分工作.我今天要做的是对UsernamePasswordAuthenticationF ...
- SpringSecurity自定义UsernamePasswordAuthenticationFilter
UsernamePasswordAuthenticationFilter介绍 UsernamePasswordAuthenticationFilter是AbstractAuthenticationPr ...
- SpringSecurity自定义注解和处理器
登录功能 添加一个配置类 @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Reso ...
- Spring-Security自定义登录页&inMemoryAuthentication验证
Spring Security是为基于Spring的应用程序提供声明式安全保护的安全性框架.框架下内容比较多,可以做到按照角色权限对请求路径进行限制.今天主要验证自定义登录页,在内存用户存储中进行请求 ...
随机推荐
- Go 1.9 sync.Map揭秘
Go 1.9 sync.Map揭秘 目录 [−] 有并发问题的map Go 1.9之前的解决方案 sync.Map Load Store Delete Range sync.Map的性能 其它 在Go ...
- B20J_2007_[Noi2010]海拔_平面图最小割转对偶图+堆优化Dij
B20J_2007_[Noi2010]海拔_平面图最小割转对偶图+堆优化Dij 题意:城市被东西向和南北向的主干道划分为n×n个区域.城市中包括(n+1)×(n+1)个交叉路口和2n×(n+1)条双向 ...
- 对Javascript 类、原型链、继承的理解
一.序言 和其他面向对象的语言(如Java)不同,Javascript语言对类的实现和继承的实现没有标准的定义,而是将这些交给了程序员,让程序员更加灵活地(当然刚开始也更加头疼)去定义类,实现继承 ...
- 对抗明文口令泄露 —— Web 前端慢 Hash
(更新:https://www.cnblogs.com/index-html/p/frontend_kdf.html ) 0x00 前言 天下武功,唯快不破.但在密码学中则不同.算法越快,越容易破. ...
- Scala 隐式转换及应用
什么是隐式转换 我们经常引入第三方库,但当我们想要扩展新功能的时候通常是很不方便的,因为我们不能直接修改其代码.scala提供了隐式转换机制和隐式参数帮我们解决诸如这样的问题. Scala中的隐式转换 ...
- Eclipse Debug调试遇到的问题
在使用Debug模式前,一定要先打好断点.快捷调试方法: 在使用过程中,可以只保留Console,Variables,Debug窗口,把其他无用的窗口最小化掉,或者删掉即可.如果要恢复删掉的试图, ...
- Polaristech 刘洋:基于 OpenResty/Kong 构建边缘计算平台
2019 年 3 月 23 日,OpenResty 社区联合又拍云,举办 OpenResty × Open Talk 全国巡回沙龙·北京站,Polaristech 技术专家刘洋在活动上做了<基于 ...
- SpringBoot框架与MyBatis集成,连接Mysql数据库
SpringBoot是一种用来简化新Spring应用初始搭建及开发过程的框架,它使用特定方式来进行配置,使得开发人员不再需要定义样板化的配置.MyBatis是一个支持普通SQL查询.存储和高级映射的持 ...
- Java进阶篇之十五 ----- JDK1.8的Lambda、Stream和日期的使用详解(很详细)
前言 本篇主要讲述是Java中JDK1.8的一些新语法特性使用,主要是Lambda.Stream和LocalDate日期的一些使用讲解. Lambda Lambda介绍 Lambda 表达式(lamb ...
- js 异步转同步
在项目中有些逻辑或者请求依赖另一个异步请求,大家常用的方法是回调函数.现在有个高大上的解决方案:await async . async 是“异步”的简写,而 await 可以认为是 async wai ...