springboot实现验证码功能
生活随笔
收集整理的這篇文章主要介紹了
springboot实现验证码功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉載自 : www.javaman.cn
1、編寫工具類生成4位隨機數
該工具類主要生成從0-9,a-z,A-Z范圍內產生的4位隨機數
/**
* 產生4位隨機字符串
*/
public static String getCheckCode() {
String base = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
int size = base.length();
Random r = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 1; i <= 4; i++) {
//產生0到size-1的隨機值
int index = r.nextInt(size);
//在base字符串中獲取下標為index的字符
char c = base.charAt(index);
//將c放入到StringBuffer中去
sb.append(c);
}
return sb.toString();
}
2、編寫常量類
用戶常量的綁定,所有的常量都可以在ConfigConsts中定義,方便管理。
import java.util.Arrays;
import java.util.List;
public interface ConfigConsts {
/**
* 驗證碼存session
*/
String IMAGE_CODE_SESSION = "IMAGE_CODE";
}
3、獲取驗證碼接口
這段代碼的主要作用是為用戶生成一個圖片驗證碼,并將其顯示在瀏覽器中。當調用該代碼對應的URL時,服務器會創建一個包含隨機驗證碼的圖片,并將此驗證碼存儲在用戶的會話中,然后將該圖片發送給用戶的瀏覽器顯示
/**
* 驗證碼
*/
@RequestMapping("/getImgCode")
public void getImgCode(HttpServletRequest request, HttpServletResponse response) {
int width = 80;
int height = 30;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//獲取畫筆
Graphics graphics = image.getGraphics();
//設置畫筆顏色為白色
graphics.setColor(Color.white);
//填充圖片
graphics.fillRect(0, 0, width, height);
//設置畫筆顏色為黑色
graphics.setColor(Color.black);
//設置字體的小大
graphics.setFont(new Font("黑體", Font.BOLD, 24));
//產生4個隨機驗證碼
String checkCode = CommonUtil.getCheckCode();
//將驗證碼放入HttpSession中
HttpSession session = request.getSession();
session.setAttribute(ConfigConsts.IMAGE_CODE_SESSION, checkCode);
//向圖片上寫入驗證碼
graphics.drawString(checkCode, 15, 25);
//將內存中的圖片輸出到瀏覽器
try {
response.setContentType("image/png");
ImageIO.write(image, "PNG", response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
4、controller跳轉到登錄頁
對“/loginPage”的GET請求,并將用戶重定向到登錄頁面。當調用這個URL時,系統會返回一個名為"login"的視圖(通常是一個HTML頁面),這個視圖通常用于顯示登錄表單,讓用戶輸入用戶名和密碼等信息。
/**
* 跳轉到登陸頁面
* @return 登陸頁面
*/
@GetMapping("/loginPage")
public String loginPage(){
return "login";
}
5、登錄界面
在Web頁面上實現一個圖形驗證碼的輸入功能
-
HTML部分:
- 創建一個表單項,內部包含兩列(使用layui的柵格系統)。
- 在第一列中,有一個標簽和一個文本輸入框。標簽用于顯示一個驗證碼圖標,輸入框用于用戶輸入圖形驗證碼。
- 在第二列中,有一個圖片元素用于顯示圖形驗證碼圖片。
-
JavaScript部分:
- 配置layui的靜態資源路徑和主入口模塊。
- 初始化時,調用
getImgCode函數加載驗證碼圖片,并渲染表單。 -
getImgCode函數通過Ajax請求從服務器獲取驗證碼圖片,并將其顯示在頁面上的圖片元素中。
這段代碼主要利用了layui框架來實現頁面的布局和交互,同時通過JavaScript和Ajax實現與服務器的通信,以獲取并顯示圖形驗證碼。
<div class="layui-form-item">
<div class="layui-row">
<div class="layui-col-xs7">
<label class="layadmin-user-login-icon layui-icon layui-icon-vercode"></label>
<input type="text" name="code" lay-verify="required" placeholder="圖形驗證碼" class="layui-input">
</div>
<div class="layui-col-xs5">
<div style="margin-left: 10px;">
<img id="codeImg" class="layadmin-user-login-codeimg">
</div>
</div>
</div>
<script>
layui.config({
base: '/static/layuiadmin/' //靜態資源所在路徑
}).extend({
index: 'lib/index' //主入口模塊
}).use(['index', 'user'], function(){
let $ = layui.$,
form = layui.form;
// 初始化
getImgCode();
form.render();
}
/**
* 獲取驗證碼
*/
function getImgCode() {
let url = ctx + '/getImgCode';
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status === 200) {
let blob = this.response;
document.getElementById("codeImg").src = window.URL.createObjectURL(blob);
}
}
xhr.send();
}
</script>
6、驗證碼過濾
校驗驗證碼的過濾器,基于Java的Spring框架。
- 該過濾器繼承了
OncePerRequestFilter,確保每次請求只被過濾一次。 - 在
doFilterInternal方法中,它首先檢查請求是否是登錄請求(通過檢查請求路徑是否為"/login"以及請求方法是否為"POST")。 - 如果是登錄請求,它會調用
validate方法來校驗驗證碼。 -
validate方法從請求中獲取驗證碼,然后與會話中存儲的驗證碼進行比對。如果驗證碼不存在、為空或不匹配,將拋出異常。 - 如果驗證碼校驗失敗,過濾器會捕獲異常,并向響應中寫入錯誤信息(以JSON格式)。
- 如果請求不是登錄請求,過濾器不會進行驗證碼校驗,直接讓請求繼續向下執行(通過調用
filterChain.doFilter)。 - 如果登錄請求成功通過驗證碼校驗,代碼會繼續執行后續的過濾器或處理器。
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
// 登陸請求
if ("/login".equals(httpServletRequest.getServletPath()) &&
"POST".equalsIgnoreCase(httpServletRequest.getMethod())){
try {
validate(httpServletRequest);
} catch (Exception exception) {
httpServletResponse.setCharacterEncoding("utf-8");
httpServletResponse.setContentType("application/json;charset=UTF-8");
PrintWriter writer = httpServletResponse.getWriter();
writer.write(JSON.toJSONString(Result.failure(exception.getMessage())));
writer.flush();
return;
}
}
// 不是一個登錄請求,不做校驗 直接通過
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
private void validate(HttpServletRequest request) {
String code = request.getParameter("code");
if (StringUtils.isBlank(code)){
throw new RuntimeException("驗證碼不能為空");
}
Object checkCode = request.getSession(false).getAttribute(ConfigConsts.IMAGE_CODE_SESSION);
if (Objects.isNull(checkCode)) {
throw new RuntimeException("驗證碼不存在");
}
if (!StringUtils.equalsIgnoreCase(code,checkCode.toString())) {
throw new RuntimeException("驗證碼不匹配");
}
request.getSession(false).removeAttribute(ConfigConsts.IMAGE_CODE_SESSION);
}
}
7、集成mysecurity
集成Spring Security的安全配置類,用于Web應用的安全性設置。
- 通過
@EnableWebSecurity和@Configuration注解,啟用并配置Spring Security。 - 使用
@EnableGlobalMethodSecurity(prePostEnabled = true)來啟用全局方法級別的安全性,允許使用例如@PreAuthorize和@PostAuthorize等注解。 - 定義了一個名為
MySecurityConfig的配置類,該類繼承自WebSecurityConfigurerAdapter,用于定制安全性設置。 - 通過
@Autowired注入了一個名為validateCodeFilter的驗證碼過濾器實例。 - 在
configure(HttpSecurity http)方法中,對應用的安全性進行了詳細配置:- 允許所有人訪問
/loginPage和/getImgCode這兩個路徑,不進行任何安全檢查。 - 對所有其他請求,需要用戶進行身份驗證(即需要登錄后才能訪問)。
- 在用戶名和密碼驗證過濾器之前,添加了一個自定義的驗證碼過濾器(
validateCodeFilter),用于在登錄過程中校驗驗證碼。
- 允許所有人訪問
這段代碼的主要目的是增強Web應用的安全性,通過添加驗證碼校驗來防止自動化登錄嘗試和暴力破解,并限制了只有經過身份驗證的用戶才能訪問應用的受保護資源。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ValidateCodeFilter validateCodeFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// 放過
.antMatchers("/loginPage", "/getImgCode").permitAll()
.anyRequest().authenticated()
.and()
// 過濾登錄驗證碼
.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
}
運行結果如下:
總結
以上是生活随笔為你收集整理的springboot实现验证码功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦见别人打台球是什么意思
- 下一篇: Tech Lead 要学会戴着镣铐跳舞