1.验证码的认证分为3种
第一种直接在contrller中添加认证
package com.hanhuide.core.controller;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
@Api(tags = "验证码")
@Slf4j
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {
@Autowired
DefaultKaptcha defaultKaptcha;
@RequestMapping("/render")
public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
byte[] captchaChallengeAsJpeg = null;
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
try {
//生产验证码字符串并保存到session中
String createText = defaultKaptcha.createText();
log.info(createText);
httpServletRequest.getSession().setAttribute("code", createText);
//使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
BufferedImage challenge = defaultKaptcha.createImage(createText);
ImageIO.write(challenge, "jpg", jpegOutputStream);
} catch (IllegalArgumentException e) {
httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
//定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
httpServletResponse.setHeader("Cache-Control", "no-store");
httpServletResponse.setHeader("Pragma", "no-cache");
httpServletResponse.setDateHeader("Expires", 0);
httpServletResponse.setContentType("image/jpeg");
ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
responseOutputStream.write(captchaChallengeAsJpeg);
responseOutputStream.flush();
responseOutputStream.close();
}
//验证码验证
@RequestMapping("/checkCode")
public boolean imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
String captchaId = (String) httpServletRequest.getSession().getAttribute("vrifyCode");
String parameter = httpServletRequest.getParameter("code");
log.info("Session vrifyCode ---->"+captchaId+"---- form code --->"+parameter);
if (!captchaId.equals(parameter)) {
log.info("错误的验证码");
return false;
} else {
return true;
}
}
}
第二种 认证是在security的基础上添加拦截器
package com.hanhuide.core.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @program: maven
* @description:
* @author: 韩惠德
* @create: 2019-12-27 17:30
* @version: 1.0
**/
@Slf4j
public class kaptchaFilter extends OncePerRequestFilter {
private static final PathMatcher pathMatcher = new AntPathMatcher();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (isProtectedUrl(request)) {
String validateCodeText = request.getParameter("validateCodeText");
logger.info(validateCodeText);
if (!kaptchaVerify(validateCodeText)) {
//手动设置异常
request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", new DisabledException("验证码输入错误"));
// 转发到错误Url
request.getRequestDispatcher("/login/error").forward(request, response);
} else {
filterChain.doFilter(request, response);
}
} else {
filterChain.doFilter(request, response);
}
}
private boolean kaptchaVerify(String validateCodeText) {
//获取当前线程绑定的request对象
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 这个validateCode是在servlet中存入session的名字code 在获取验证码的时候添加到session中
String validateCode = ((String) request.getSession().getAttribute("code")).toLowerCase();
validateCodeText = validateCodeText.toLowerCase();
log.info("验证码:" + validateCode + "用户输入:" + validateCodeText);
return validateCode.equals(validateCodeText);
}
/**
* 拦截请求登录页面 为post的请求
* @param request
* @return
*/
private boolean isProtectedUrl(HttpServletRequest request) {
return "POST".equals(request.getMethod()) && pathMatcher.match("/login", request.getServletPath());
}
}
并将拦截器注入到spring中
http.addFilterBefore(new kaptchaFilter(), UsernamePasswordAuthenticationFilter.class);
package com.hanhuide.core.config;
//import com.hanhuide.core.filter.JwtAuthenticationTokenFilter;
import com.hanhuide.core.filter.kaptchaFilter;
import com.hanhuide.core.handler.*;
import com.hanhuide.core.service.impl.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
* @program: maven
* @description:
* @author: 韩惠德
* @create: 2019-12-26 11:56
* @version: 1.0
**/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AjaxAuthenticationEntryPoint authenticationEntryPoint; // 未登陆时返回 JSON 格式的数据给前端(否则为 html)
@Autowired
private AjaxAuthenticationSuccessHandler authenticationSuccessHandler; // 登录成功返回的 JSON 格式数据给前端(否则为 html)
@Autowired
private AjaxAuthenticationFailureHandler authenticationFailureHandler; // 登录失败返回的 JSON 格式数据给前端(否则为 html)
@Autowired
private AjaxLogoutSuccessHandler logoutSuccessHandler; // 注销成功返回的 JSON 格式数据给前端(否则为 登录时的 html)
@Autowired
private AjaxAccessDeniedHandler accessDeniedHandler; // 无权访问返回的 JSON 格式数据给前端(否则为 403 html 页面)
// @Autowired
// private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; //jwt验证
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private CustomAuthenticationDetailsSource authenticationDetailsSource;
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/kaptcha/render").permitAll().anyRequest().authenticated();// 如果有允许匿名的url,填在下面
http.httpBasic().authenticationEntryPoint(authenticationEntryPoint);
http.formLogin().loginPage("/login").defaultSuccessUrl("/").permitAll()
.authenticationDetailsSource(authenticationDetailsSource).successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler)
.permitAll();
http.logout().logoutSuccessHandler(logoutSuccessHandler);
http.rememberMe().rememberMeParameter("remember-me").userDetailsService(userDetailsService).tokenValiditySeconds(10000);
http.exceptionHandling().accessDeniedHandler(accessDeniedHandler); // 无权访问 JSON 格式的数据
http.addFilterBefore(new kaptchaFilter(), UsernamePasswordAuthenticationFilter.class);
//使用jwt的Authentication,来解析过来的请求是否有token
// http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
//配置取消session管理,又Jwt来获取用户状态,否则即使token无效,也会有session信息,依旧判断用户为登录状态
// http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// 关闭CSRF跨域
http.csrf().disable();
}
@Override
public void configure(WebSecurity web) throws Exception {
// 设置拦截忽略文件夹,可以对静态资源放行
web.ignoring().antMatchers("/css/**", "/js/**", "/fonts/**", "/images/**", "/vendor/**");
}
}
第三种方式为 重新定义security的登录用户类
首先自定义用户登录时携带的信息类
package com.hanhuide.core.model;
import com.google.code.kaptcha.Constants;
import lombok.Data;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import javax.servlet.http.HttpServletRequest;
/**
* @program: maven
* @description: 自定义用户登录时携带的额外信息
* @author: 韩惠德
* @create: 2019-12-30 14:36
* @version: 1.0
**/
@Data
public class CustomerAuthDetails extends WebAuthenticationDetails {
private final String verifyCode;
private final String captchSession;
private final String username;
private final String password;
public CustomerAuthDetails(HttpServletRequest request) {
super(request);
this.verifyCode = request.getParameter("validateCodeText");
this.captchSession = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
this.username = request.getParameter("username");
this.password = request.getParameter("password");
}
@Override
public String toString() {
return "CustomerAuthDetails{" +
"verifyCode='" + verifyCode + '\'' +
", captchSession='" + captchSession + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
其次将自定义的添加信息填充到security中
package com.hanhuide.core.handler;
import com.hanhuide.core.model.CustomAuthDetails;
import org.springframework.security.authentication.AuthenticationDetailsSource;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
/**
* @program: maven
* @description: 用于在Spring Security登录过程中对用户的登录信息的详细信息进行填充
* @author: 韩惠德
* @create: 2019-12-30 14:41
* @version: 1.0
**/
@Component("authenticationDetailsSource")
public class CustomAuthenticationDetailsSource implements AuthenticationDetailsSource {
@Override
public WebAuthenticationDetails buildDetails(HttpServletRequest request) {
return new CustomAuthDetails(request);
}
}
接着讲填充信息类注入到secutity 配置文件中
http.formLogin().loginPage("/login").defaultSuccessUrl("/").permitAll()
.authenticationDetailsSource(authenticationDetailsSource).successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler)
.permitAll();
替换security自定义的登录认证
/**
* 自定义的登录认证取代原有的security认证
* @param auth
* @throws Exception
*/
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
// }
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider);
}
源码
package com.hanhuide.core.config;
//import com.hanhuide.core.filter.JwtAuthenticationTokenFilter;
import com.hanhuide.core.filter.kaptchaFilter;
import com.hanhuide.core.handler.*;
import com.hanhuide.core.service.impl.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
* @program: maven
* @description:
* @author: 韩惠德
* @create: 2019-12-26 11:56
* @version: 1.0
**/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationEntryPoint authenticationEntryPoint; // 未登陆时返回 JSON 格式的数据给前端(否则为 html)
@Autowired
private CustomAuthenticationSuccessHandler authenticationSuccessHandler; // 登录成功返回的 JSON 格式数据给前端(否则为 html)
@Autowired
private CustomAuthenticationFailureHandler authenticationFailureHandler; // 登录失败返回的 JSON 格式数据给前端(否则为 html)
@Autowired
private CustomLogoutSuccessHandler logoutSuccessHandler; // 注销成功返回的 JSON 格式数据给前端(否则为 登录时的 html)
@Autowired
private CustomAccessDeniedHandler accessDeniedHandler; // 无权访问返回的 JSON 格式数据给前端(否则为 403 html 页面)
// @Autowired
// private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter; //jwt验证
@Autowired
private CustomUserDetailsService userDetailsService;
@Autowired
private CustomAuthenticationDetailsSource authenticationDetailsSource;
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
/**
* 自定义的登录认证取代原有的security认证
* @param auth
* @throws Exception
*/
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
// }
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/kaptcha/render").permitAll().anyRequest().authenticated();// 如果有允许匿名的url,填在下面
http.httpBasic().authenticationEntryPoint(authenticationEntryPoint);
http.formLogin().loginPage("/login").defaultSuccessUrl("/").permitAll()
.authenticationDetailsSource(authenticationDetailsSource).successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler)
.permitAll();
http.logout().logoutSuccessHandler(logoutSuccessHandler);
http.rememberMe().rememberMeParameter("remember-me").userDetailsService(userDetailsService).tokenValiditySeconds(10000);
http.exceptionHandling().accessDeniedHandler(accessDeniedHandler); // 无权访问 JSON 格式的数据
// http.addFilterBefore(new kaptchaFilter(), UsernamePasswordAuthenticationFilter.class);
//使用jwt的Authentication,来解析过来的请求是否有token
// http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
//配置取消session管理,又Jwt来获取用户状态,否则即使token无效,也会有session信息,依旧判断用户为登录状态
// http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// 关闭CSRF跨域
http.csrf().disable();
}
@Override
public void configure(WebSecurity web) throws Exception {
// 设置拦截忽略文件夹,可以对静态资源放行
web.ignoring().antMatchers("/css/**", "/js/**", "/fonts/**", "/images/**", "/vendor/**");
}
}
完事 有疑问请留言!!!!!!!!!!!!!!!!!