溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java如何實現(xiàn)OAuth2.0授權(quán)系統(tǒng)的驗證碼功能

發(fā)布時間:2022-02-24 10:22:20 來源:億速云 閱讀:271 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容介紹了“Java如何實現(xiàn)OAuth2.0授權(quán)系統(tǒng)的驗證碼功能”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

1.集成EasyCaptcha:

<dependencies>
   <dependency>
      <groupId>com.github.whvcse</groupId>
      <artifactId>easy-captcha</artifactId>
      <version>1.6.2</version>
   </dependency>
</dependencies>

2.生成驗證碼并保存到Redis中:

/**
     * 驗證碼
     *
     * @return
     */
    @GetMapping("/captcha")
    public Result captcha() {
 
        String captchaKey = "captcha_" + UUID.randomUUID();
        // 三個參數(shù)分別為寬、高、位數(shù)
        SpecCaptcha captcha = new SpecCaptcha(130, 60, 4);
        // 設(shè)置字體 有默認(rèn)字體,可以不用設(shè)置
        captcha.setFont(new Font("Verdana", Font.PLAIN, 32));
        // 設(shè)置類型,純數(shù)字、純字母、字母數(shù)字混合
        captcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        log.info("key: [{}] ,code: [{}]", captchaKey, captcha.text());
        // 存入Redis ,默認(rèn)兩分鐘
        redisBaseUtil.set(captchaKey, captcha.text(), 2, TimeUnit.MINUTES);
        Map<String, Object> map = new HashMap<>(4);
        map.put("captchaKey", captchaKey);
        map.put("image", captcha.toBase64());
        return Result.success(map);
 
    }

3. 校驗驗證碼的Filter: 

package com.hanxiaozhang.filter;
 
import com.hanxiaozhang.constant.Constant;
import com.hanxiaozhang.redis.util.RedisUtil;
import com.hanxiaozhang.result.ResultCode;
import com.hanxiaozhang.result.Result;
import com.hanxiaozhang.util.JsonUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
 
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
 
/**
 * 〈一句話功能簡述〉<br>
 * 〈驗證碼過濾器〉
 *
 * @author hanxinghua
 * @create 2021/4/4
 * @since 1.0.0
 */
@Slf4j
@Component
public class CaptchaFilter extends ZuulFilter {
 
    @Autowired
    private RedisUtil redisBaseUtil;
 
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
 
    @Override
    public int filterOrder() {
        return 0;
    }
 
    @Override
    public boolean shouldFilter() {
        return true;
    }
 
    @Override
    public Object run() {
 
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest serverHttpRequest = currentContext.getRequest();
        String uri = serverHttpRequest.getRequestURI();
        if (uri.contains("/oauth/token")) {
            String method = serverHttpRequest.getMethod();
            // 處理跨域Post發(fā)送兩次請求
            if (Constant.OPTIONS.equals(method)) {
                return null;
            }
            Map<String, String[]> parameterMap = serverHttpRequest.getParameterMap();
            String[] captchaKeys = null, captchaCodes = null;
            if (!parameterMap.isEmpty()
                    && (captchaKeys = parameterMap.get("captcha_key")) != null
                    && (captchaCodes = parameterMap.get("captcha_code")) != null) {
                String captchaKey = captchaKeys[0];
                String captchaCode = captchaCodes[0];
                log.info("Request Captcha Parameters: key: [{}] ,code: [{}]", captchaKey, captchaCode);
                String redisCaptchaCode = redisBaseUtil.get(captchaKey);
                String responseBody = null;
                if (redisCaptchaCode == null) {
                    responseBody = JsonUtil.beanToJson(Result.error(ResultCode.LOGIN_CAPTCHA_EXPIRE));
                } else if (!captchaCode.trim().equalsIgnoreCase(redisCaptchaCode)) {
                    responseBody = JsonUtil.beanToJson(Result.error(ResultCode.LOGIN_CAPTCHA_ERROR));
                }
                if (responseBody != null) {
                    currentContext.setSendZuulResponse(false);
                    currentContext.setResponseStatusCode(200);
                    currentContext.getResponse().setContentType(Constant.APP_JSON_UTF_8);
                    log.info("Response Parameters: 
 [{}]", responseBody);
                    currentContext.setResponseBody(responseBody);
                }
            }
        }
        return null;
    }
}

 4.使用,這里使用《Idea中HTTP Client請求測試工具》:

4.1 獲取驗證碼:

GET http://localhost/api/system/captcha

4.2 校驗驗證碼:

POST  http://localhost/api/system/oauth/token?username={{username}}&password={{password}}&grant_type=password&scope={{scope}}&client_id={{client_id}}&client_secret={{client_secret}}&captcha_key=captcha_23cacfe5-2751-44af-a34d-5e795caeb46a&captcha_code=5594

“Java如何實現(xiàn)OAuth2.0授權(quán)系統(tǒng)的驗證碼功能”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI