下面我来为你讲解SpringSecurity添加图形验证码认证实现的完整攻略。
1. 引入依赖
在pom.xml
文件中添加以下依赖:
<!--验证码依赖-->
<dependency>
<groupId>com.github.axolo</groupId>
<artifactId>image-verify-code-spring-boot-starter</artifactId>
<version>1.0.4</version>
</dependency>
2. 配置验证码
在application.properties
文件中添加以下配置:
verify-code.enabled=true # 启用验证码
verify-code.url-patterns=/login # 验证码拦截的地址
verify-code.image.width=220 # 验证码图片宽度
verify-code.image.height=50 # 验证码图片高度
verify-code.number.chars=4 # 验证码字符数量
verify-code.string.chars=acdefhjkmnpqrstuvwxyz2345678 # 验证码字符源
3. 实现验证码校验逻辑
在实现了UserDetailsService
接口的类中添加验证方法:
public void validateVerifyCode(HttpServletRequest request) {
VerifyCode verifyCode = (VerifyCode) request.getSession().getAttribute(VerifyCode.VERIFY_CODE);
if (verifyCode == null) {
throw new AuthenticationServiceException("验证码不能为空");
}
String inputVerifyCode = request.getParameter("code");
if (StringUtils.isBlank(inputVerifyCode)) {
throw new AuthenticationServiceException("验证码不能为空");
}
if (!inputVerifyCode.equalsIgnoreCase(verifyCode.getCode())) {
throw new AuthenticationServiceException("验证码错误");
}
}
4. 自定义UsernamePasswordAuthenticationFilter
继承UsernamePasswordAuthenticationFilter
,重写attemptAuthentication
方法,实现验证码校验逻辑:
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (request.getMethod().equals("POST")) {
validateVerifyCode(request);
}
return super.attemptAuthentication(request, response);
}
}
5. 添加过滤器链
在WebSecurityConfigurerAdapter
的子类中配置自定义过滤器:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/css/**", "/js/**", "/fonts/**", "/index").permitAll()
.antMatchers("/users/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login").failureUrl("/login-error");
}
@Bean
public CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
filter.setAuthenticationSuccessHandler(new LoginSuccessHandler());
filter.setAuthenticationFailureHandler(new LoginFailureHandler());
filter.setFilterProcessesUrl("/login");
filter.setAuthenticationManager(authenticationManagerBean());
return filter;
}
示例1
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
public void doLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception {
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", null);
Authentication authentication = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
session.setAttribute("user", authentication.getPrincipal());
response.sendRedirect("/");
} catch (AuthenticationException e) {
request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", e);
response.sendRedirect("/login?error");
}
}
示例2
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest == null) {
super.onAuthenticationSuccess(request, response, authentication);
return;
}
response.sendRedirect(savedRequest.getRedirectUrl());
}
}
以上是添加图形验证码认证实现的完整攻略,希望对你有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringSecurity添加图形验证码认证实现 - Python技术站