<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
@Configuration
public class CaptchaConfig {
@Bean
public Producer captcha() {
// 配置图形验证码的基本参数
Properties properties = new Properties();
// 图片宽度
properties.setProperty("kaptcha.image.width", "150");
// 图片长度
properties.setProperty("kaptcha.image.height", "50");
// 字符集
properties.setProperty("kaptcha.textproducer.char.string", "0123456789");
// 字符长度
properties.setProperty("kaptcha.textproducer.char.length", "4");
Config config = new Config(properties);
// 使用默认的图形验证码实现,当然也可以自定义实现
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
@Controller
public class CaptchaController {
@Autowired
private Producer captchaProducer;
@GetMapping("/captcha.jpg")
public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 设置内容类型
response.setContentType("image/jpeg");
// 创建验证码文本
String capText = captchaProducer.createText();
// 将验证码文本设置到session
request.getSession().setAttribute("captcha", capText);
// 创建验证码图片
BufferedImage bi = captchaProducer.createImage(capText);
// 获取响应输出流
ServletOutputStream out = response.getOutputStream();
// 将图片验证码数据写到响应输出流
ImageIO.write(bi, "jpg", out);
// 推送并关闭响应输出流
try {
out.flush();
} finally {
out.close();
}
}
}
public class VerificationCodeException extends AuthenticationException {
public VerificationCodeException () {
super("图形验证码校验失败");
}
}
/**
* 基于过滤器实现图形验证码的验证功能,这属于Servlet层面,简单易理解.
*/
public class VerificationCodeFilter extends OncePerRequestFilter {
private AuthenticationFailureHandler authenticationFailureHandler = new SecurityAuthenticationFailureHandler();
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
// 非登录请求不校验验证码,直接放行
if (!"/login".equals(httpServletRequest.getRequestURI())) {
filterChain.doFilter(httpServletRequest, httpServletResponse);
} else {
try {
//校验验证码
verificationCode(httpServletRequest);
//验证码校验通过后,对请求进行放行
filterChain.doFilter(httpServletRequest, httpServletResponse);
} catch (VerificationCodeException e) {
authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
}
}
}
public void verificationCode (HttpServletRequest httpServletRequest) throws VerificationCodeException {
HttpSession session = httpServletRequest.getSession();
String savedCode = (String) session.getAttribute("captcha");
if (!StringUtils.isEmpty(savedCode)) {
// 随手清除验证码,不管是失败还是成功,所以客户端应在登录失败时刷新验证码
session.removeAttribute("captcha");
}
String requestCode = httpServletRequest.getParameter("captcha");
// 校验不通过抛出异常
if (StringUtils.isEmpty(requestCode) || StringUtils.isEmpty(savedCode) || !requestCode.equals(savedCode)) {
throw new VerificationCodeException();
}
}
}
/**
* @Author: 一一哥
* 增加图形验证码功能.
*/
@EnableWebSecurity(debug = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/api/**")
.hasRole("ADMIN")
.antMatchers("/user/api/**")
.hasRole("USER")
.antMatchers("/app/api/**", "/captcha.jpg")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.failureHandler(new SecurityAuthenticationFailureHandler())
.successHandler(new SecurityAuthenticationSuccessHandler())
.loginPage("/myLogin.html")
.loginProcessingUrl("/login")
.permitAll()
.and()
.csrf()
.disable();
//将过滤器添加在UsernamePasswordAuthenticationFilter之前
http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
<body>
<div class="login">
<h2>Access Form</h2>
<div class="login-top">
<h1>登录验证</h1>
<form action="/login" method="post">
<input type="text" name="username" placeholder="username" />
<input type="password" name="password" placeholder="password" />
<div style="display: flex;">
<!-- 新增图形验证码的输入框 -->
<input type="text" name="captcha" placeholder="captcha" />
<!-- 图片指向图形验证码API -->
<img src="/captcha.jpg" alt="captcha" height="50px" width="150px" style="margin-left: 20px;">
</div>
<div class="forgot">
<a href="#">忘记密码</a>
<input type="submit" value="登录" >
</div>
</form>
</div>
<div class="login-bottom">
<h3>新用户 <a href="#">注 册</a></h3>
</div>
</div>
</body>

接下来我们输入正确的用户名、密码、验证码后,就可以成功的登录进去访问web接口了。
原文作者:Java架构栈;如有侵权,请联系管理员删除。