一对扶、開發(fā)生成圖形驗證碼接口
1.根據(jù)隨機數(shù)生成圖片
因為不管是手機APP還是瀏覽器都可能會用到,所以我寫到了core模塊惭缰。
2.將隨機數(shù)存到Session中
3.再將生成的圖片寫到接口的響應(yīng)中
首先定義一個實體類,封裝驗證碼的信息笼才,其中包含圖片信息漱受,驗證碼,以及過期時間
package com.tinner.security.core.validate.code;
import java.awt.image.BufferedImage;
import java.time.LocalDateTime;
public class ImageCode {
private BufferedImage image;
private String code;
private LocalDateTime expireTime;
public ImageCode(BufferedImage image, String code, int expireTime) {
this.image = image;
this.code = code;
this.expireTime = LocalDateTime.now().plusSeconds(expireTime);
}
public boolean isExpried(){
return LocalDateTime.now().isAfter(expireTime);
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public LocalDateTime getExpireTime() {
return expireTime;
}
public void setExpireTime(LocalDateTime expireTime) {
this.expireTime = expireTime;
}
}
注意:在重寫構(gòu)造方法的時候骡送,入?yún)⑹且粋€int類型的一個過期時間昂羡,就是一個秒,一般過期時間都是60秒摔踱,然后在構(gòu)造方法里面 this.expireTime = LocalDateTime.now().plusSeconds(expireTime);這個代碼指的是將過期時間設(shè)為一個未來的一個時間虐先。這個類中還有一個判斷驗證碼是否過期的一個方法isExpried。
代碼如下
@RestController
public class ValidateCodeController {
private static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@GetMapping("/code/image")
public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
ImageCode imageCode = createImageCode(request);
sessionStrategy.setAttribute(new ServletWebRequest(request),SESSION_KEY,imageCode);
ImageIO.write(imageCode.getImage(),"JPEG",response.getOutputStream());
}
private ImageCode createImageCode(HttpServletRequest request) {
int width = 67;
int height = 23;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
g.dispose();
return new ImageCode(image, sRand, 60);
}
/**
* 生成隨機背景條紋
*
* @param fc
* @param bc
* @return
*/
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
二派敷、在認(rèn)證流程中加入圖形驗證碼的校驗
在SpringSecurity并沒有提供圖像驗證碼的過濾器蛹批,但是我們可以在過濾器鏈中加入我們自己寫的圖形過濾器。就是在UsernamePasswordAuthenticationFilter過濾器之前加一個自己寫的過濾器篮愉。在自己寫的過濾器里面去執(zhí)行校驗的邏輯腐芍,如果驗證通過則將請求通過,如果驗證失敗就拋出異常试躏。
代碼:
package com.tinner.security.core.validate.code;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
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;
public class ValidateCodeFilter extends OncePerRequestFilter {
public AuthenticationFailureHandler getAuthenticationFailureHandler() {
return authenticationFailureHandler;
}
public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
this.authenticationFailureHandler = authenticationFailureHandler;
}
private AuthenticationFailureHandler authenticationFailureHandler;
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
if (StringUtils.equals("/authentication/form",httpServletRequest.getRequestURI()) && StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(),"post")){
try {
validate(new ServletWebRequest(httpServletRequest));
}catch (ValidateCodeException e){
authenticationFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
return ;
}
}
filterChain.doFilter(httpServletRequest,httpServletResponse);
}
/**
* 校驗邏輯
* @param
*/
public void validate(ServletWebRequest request) throws ServletRequestBindingException {
ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(request,ValidateCodeController.SESSION_KEY);
String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),"imageCode");
if (StringUtils.isBlank(codeInRequest)) {
throw new ValidateCodeException("驗證碼的值不能為空");
}
if (codeInSession == null) {
throw new ValidateCodeException( "驗證碼不存在");
}
if (codeInSession.isExpried()) {
sessionStrategy.removeAttribute(request, ValidateCodeController.SESSION_KEY);
throw new ValidateCodeException( "驗證碼已過期");
}
if (!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
throw new ValidateCodeException("驗證碼不匹配");
}
sessionStrategy.removeAttribute(request, ValidateCodeController.SESSION_KEY);
}
}
其中我還定義了一個異常信息:
public class ValidateCodeException extends AuthenticationException {
public ValidateCodeException(String msg) {
super(msg);
}
private static final long serialVersionUID = 1422465195260228715L;
}
我來繼承了AuthenticationException 猪勇,這個異常是安全框架默認(rèn)提供的一個異常。
然后是重寫頁面index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登錄</title>
</head>
<body>
<h1>標(biāo)準(zhǔn)登錄頁面</h1>
<h3>表單登錄</h3>
<form action="/authentication/form" method="post">
<table>
<tr>
<td>用戶名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>密碼:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>驗證碼:</td>
<td>
<input type="text" name="imageCode"/>
<img src="/code/image">
</td>
</tr>
<tr>
<td colspan="2"><button type="submit">登錄</button></td>
</tr>
</table>
</form>
</body>
</html>
三颠蕴、配置SpringSecurity的config
package com.tinner.security.browser;
import com.tinner.security.core.properties.SecurityProperties;
import com.tinner.security.core.validate.code.ValidateCodeController;
import com.tinner.security.core.validate.code.ValidateCodeFilter;
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.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import java.io.File;
/**
* WebSecurityConfigurerAdapter是springSecurity提供的一個適配器類
*/
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SecurityProperties securityProperties;
@Autowired
private AuthenticationSuccessHandler tinnerAuthentivationSuccessHandler;
@Autowired
private AuthenticationFailureHandler tinnerAuthentivationFailureHandler;
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
validateCodeFilter.setAuthenticationFailureHandler(tinnerAuthentivationFailureHandler);
// super.configure(http);
//實現(xiàn)的效果:讓它去表單登錄泣刹,而不是alert框
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
.formLogin()
.loginPage("/authentication/require")
.loginProcessingUrl("/authentication/form")
.successHandler(tinnerAuthentivationSuccessHandler)
.failureHandler(tinnerAuthentivationFailureHandler)
// http.httpBasic()
.and()
.authorizeRequests()//對請求進行授權(quán)
.antMatchers("/authentication/require",securityProperties.getBrowser().getLoginPage(),"/code/image").permitAll()
.anyRequest()//任何請求
.authenticated()
.and().csrf().disable();//都需要身份認(rèn)證
}
}
這樣助析,項目就可以運行了,但是在我登錄失敗之后它會彈出堆棧信息椅您,并不能顯示出我的校驗的信息外冀。因此我還得重寫我之前的TinnerAuthentivationFailureHandler的onAuthenticationFailure方法,之前是將異常全部寫入httpServletResponse中襟沮,現(xiàn)在只將異常的message寫進 去即可
package com.tinner.security.browser.authentication;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tinner.security.browser.support.SimpleResponse;
import com.tinner.security.core.properties.LoginType;
import com.tinner.security.core.properties.SecurityProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component("tinnerAuthentivationFailureHandler")
//public class TinnerAuthentivationFailureHandler implements AuthenticationFailureHandler {
public class TinnerAuthentivationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
private Logger LOGGER = LoggerFactory.getLogger(this.getClass());
@Autowired
private ObjectMapper objectMapper;
@Autowired
private SecurityProperties securityProperties;
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
LOGGER.info("登錄失敗");
if (LoginType.JSON.equals(securityProperties.getBrowser().getLoginType())){
httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
httpServletResponse.setContentType("application/json;charset=UTF-8");
httpServletResponse.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(e.getMessage())));
}else{
super.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
}
}
}