【Spring Security系列】Spring Security 过滤器详解与基于JDBC的认证实现
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
// 继承UsernamePasswordAuthenticationFilter,实现自定义登录过滤器
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
// 重写attemptAuthentication方法以支持非标准登录请求
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
// 从请求中获取用户名和密码
String username = obtainUsername(request);
String password = obtainPassword(request);
// 这里可以添加额外的验证逻辑
// 创建认证令牌
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
// 返回认证信息
return this.getAuthenticationManager().authenticate(authenticationToken);
}
// 可以重写其他需要的方法
}
// 配置自定义的认证过滤器
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private CustomAuthenticationProvider authenticationProvider;
@Autowired
private CustomAuthenticationFilter authenticationFilter;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 其他配置...
.authenticationEntryPoint(authenticationEntryPoint)
.addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
// 自定义AuthenticationProvider
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserDetailsService userDetailsService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// 从authentication获取用户名和密码
String name = authentication.getName();
String password = authentication.getCredentials().toString();
// 使用数据库服务查询用户详情
UserDetails userDetails = userDetailsService.loadUserByUsername(name);
// 比较密码
if (passwordEncoder.matches(password, userDetails.getPassword())) {
/
评论已关闭