SpringBoot-Google二步驗證


SpringBoot-Google二步驗證

  • 概念:Google身份驗證器Google Authenticator是谷歌推出的基於時間的一次性密碼(Time-based One-time Password,簡稱TOTP),只需要在手機上安裝該APP,就可以生成一個隨着時間變化的一次性密碼,用於帳戶驗證。
  • Google身份驗證器是一款基於時間與哈希的一次性密碼算法的兩步驗證軟件令牌,此軟件用於Google的認證服務。此項服務所使用的算法已列於RFC 6238和RFC 4226中。

一、流程

  • 用戶請求服務器生成密鑰
  • 服務器生成一個密鑰並與用戶信息進行關聯,並返回密鑰(類似:XX57HWC7D2FA4X4GLOHOASTGPMVI5EFA)和一個二維碼信息(此步驟還沒有綁定)
  • 用戶把返回的二維碼信息傳給服務器,生成一個二維碼
    信息大概長這樣的:otpauth://totp/https%3A%2F%2Fwww.lrshuai.top%3Arstyro?secret=XX57HWC7D2FA4X4GLOHOASTGPMVI5EFA&issuer=https%3A%2F%2Fwww.lrshuai.top
  • 用戶通過身份驗證器掃描二維碼即可生成一個動態的驗證碼
  • 用戶傳當前動態的驗證碼和密鑰給服務器,校驗密鑰的正確性(此密鑰與用戶真正的綁定)
  • 上面有些步驟不必須的,看需求,可以簡化為兩步。
  • 1、生成密鑰
  • 2、掃碼
    上面那么多只是為了准確性而已

二、安裝身份驗證器

  • 客戶端每30秒就會生成新的驗證碼
  • 界面大概如下:

三、代碼實現

1、前言

  • 為了比較真實所以添加了注冊和登錄接口
  • 為了方便集成了Swagger-ui 和全部是GET請求,不會用Swagger-ui,就直接地址欄請求或者Postman都可
  • 注冊用戶全部放Redis
  • 登錄與Google校驗,也以注解方式實現
  • 登錄以token方式,所以請求其他接口的時候都要帶上token,可以把token放在header里面

2、代碼

UserController
  • 控制層接口
  • 流程從上往下執行即可
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import top.lrshuai.googlecheck.annotation.NeedLogin;
import top.lrshuai.googlecheck.base.BaseController;
import top.lrshuai.googlecheck.common.Result;
import top.lrshuai.googlecheck.dto.GoogleDTO;
import top.lrshuai.googlecheck.dto.LoginDTO;
import top.lrshuai.googlecheck.service.UserService;
import top.lrshuai.googlecheck.utils.QRCodeUtil;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

@Controller
@RequestMapping("/user")
@Api(tags = "用戶模塊")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @GetMapping("/register")
    @ApiOperation("注冊")
    @ResponseBody
    public Result register(LoginDTO dto) throws Exception {
        return userService.register(dto);
    }


    @GetMapping("/login")
    @ApiOperation("登錄")
    @ResponseBody
    public Result login(LoginDTO dto)throws Exception{
        return userService.login(dto);
    }


    @GetMapping("/generateGoogleSecret")
    @ResponseBody
    @NeedLogin
    @ApiOperation("生成google密鑰")
    public Result generateGoogleSecret()throws Exception{
        return userService.generateGoogleSecret(this.getUser());
    }

    /**
     * 顯示一個二維碼圖片
     * @param secretQrCode   generateGoogleSecret接口返回的:secretQrCode
     * @param response
     * @throws Exception
     */
    @GetMapping("/genQrCode")
    @ApiOperation("生成二維碼")
    public void genQrCode(String secretQrCode, HttpServletResponse response) throws Exception{
        response.setContentType("image/png");
        OutputStream stream = response.getOutputStream();
        QRCodeUtil.encode(secretQrCode,stream);
    }


    @GetMapping("/bindGoogle")
    @ResponseBody
    @NeedLogin
    @ApiOperation("綁定google驗證")
    public Result bindGoogle(GoogleDTO dto)throws Exception{
        return userService.bindGoogle(dto,this.getUser(),this.getRequest());
    }

    @GetMapping("/googleLogin")
    @ResponseBody
    @NeedLogin
    @ApiOperation("google登錄")
    public Result googleLogin(Long code) throws Exception{
        return userService.googleLogin(code,this.getUser(),this.getRequest());
    }


    @GetMapping("/getData")
    @NeedLogin(google = true)
    @ApiOperation("獲取用戶數據與token數據,前提需要google認證才能訪問")
    @ResponseBody
    public Result getData()throws Exception{
        return userService.getData();
    }

}
UserService
  • 服務層,業務代碼
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.lrshuai.encryption.MDUtil;
import top.lrshuai.googlecheck.common.*;
import top.lrshuai.googlecheck.dto.GoogleDTO;
import top.lrshuai.googlecheck.dto.LoginDTO;
import top.lrshuai.googlecheck.entity.User;
import top.lrshuai.googlecheck.utils.GoogleAuthenticator;
import top.lrshuai.googlecheck.utils.Tools;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 獲取緩存中的數據
     * @return
     */
    public Result getData(){
        Map<String,Object> data = new HashMap<>();
        setData(CacheKey.REGISTER_USER_KEY,data);
        setData(CacheKey.TOKEN_KEY_LOGIN_KEY,data);
        return Result.ok(data);
    }

    public void setData(String keyword,Map<String,Object> data){
        Set<String> keys = redisTemplate.keys(keyword);
        Iterator<String> iterator = keys.iterator();
        while (iterator.hasNext()){
            String key = iterator.next();
            data.put(key,redisTemplate.opsForValue().get(key));
        }
    }

    /**
     * 注冊
     * @param dto
     * @return
     * @throws Exception
     */
    public Result register(LoginDTO dto) throws Exception {
        User user = new User();
        user.setUserId(Tools.getUUID());
        user.setUsername(dto.getUsername());
        user.setPassword(MDUtil.bcMD5(dto.getPassword()));
        addUser(user);
        return Result.ok();
    }


    //獲取用戶
    public User getUser(String username){
        User cacheUser = (User) redisTemplate.opsForValue().get(String.format(CacheKey.REGISTER_USER, username));
        return cacheUser;
    }

    //添加注冊用戶
    public void addUser(User user){
        if(user == null) throw new ApiException(ApiResultEnum.ERROR_NULL);
        User isRepeat = getUser(user.getUsername());
        if(isRepeat != null ){
            throw new ApiException(ApiResultEnum.USER_IS_EXIST);
        }
        redisTemplate.opsForValue().set(String.format(CacheKey.REGISTER_USER, user.getUsername()),user,1, TimeUnit.DAYS);
    }

    //更新token用戶
    public void updateUser(User user,HttpServletRequest request){
        if(user == null) throw new ApiException(ApiResultEnum.ERROR_NULL);
        redisTemplate.opsForValue().set(Tools.getTokenKey(request,CacheEnum.LOGIN),user,1, TimeUnit.DAYS);
    }


    /**
     * 登錄
     * @param dto
     * @return
     * @throws Exception
     */
    public Result login(LoginDTO dto) throws Exception {
        User user = getUser(dto.getUsername());
        if(user == null){
            throw new ApiException(ApiResultEnum.USER_NOT_EXIST);
        }
        if(!user.getPassword().equals(MDUtil.bcMD5(dto.getPassword()))){
            throw new ApiException(ApiResultEnum.USERNAME_OR_PASSWORD_IS_WRONG);
        }
        //隨機生成token
        String token = Tools.getUUID();
        redisTemplate.opsForValue().set(String.format(CacheKey.TOKEN_KEY_LOGIN,token),user,1,TimeUnit.DAYS);
        Map<String,Object> data = new HashMap<>();
        data.put(Consts.TOKEN,token);
        return Result.ok(data);
    }

    /**
     * 生成Google 密鑰
     * secret:密鑰
     * secretQrCode:Google Authenticator 掃描條形碼的內容
     * @param user
     * @return
     */
    public Result generateGoogleSecret(User user){
        //Google密鑰
        String randomSecretKey = GoogleAuthenticator.getRandomSecretKey();
        String googleAuthenticatorBarCode = GoogleAuthenticator.getGoogleAuthenticatorBarCode(randomSecretKey, user.getUsername(), "https://www.lrshuai.top");
        Map<String,Object> data = new HashMap<>();
        //Google密鑰
        data.put("secret",randomSecretKey);
        //用戶二維碼內容
        data.put("secretQrCode",googleAuthenticatorBarCode);
        return Result.ok(data);
    }


    /**
     * 綁定Google
     * @param dto
     * @param user
     * @return
     */
    public Result bindGoogle(GoogleDTO dto, User user, HttpServletRequest request){
        if(!StringUtils.isEmpty(user.getGoogleSecret())){
            throw new ApiException(ApiResultEnum.GOOGLE_IS_BIND);
        }
        boolean isTrue = GoogleAuthenticator.check_code(dto.getSecret(), dto.getCode(), System.currentTimeMillis());
        if(!isTrue){
            throw new ApiException(ApiResultEnum.GOOGLE_CODE_NOT_MATCH);
        }
        User cacheUser = getUser(user.getUsername());
        cacheUser.setGoogleSecret(dto.getSecret());
        updateUser(cacheUser,request);
        return Result.ok();
    }

    /**
     * Google登錄
     * @param code
     * @param user
     * @return
     */
    public Result googleLogin(Long code,User user,HttpServletRequest request){
        if(StringUtils.isEmpty(user.getGoogleSecret())){
            throw new ApiException(ApiResultEnum.GOOGLE_NOT_BIND);
        }
        boolean isTrue = GoogleAuthenticator.check_code(user.getGoogleSecret(), code, System.currentTimeMillis());
        if(!isTrue){
            throw new ApiException(ApiResultEnum.GOOGLE_CODE_NOT_MATCH);
        }
        redisTemplate.opsForValue().set(Tools.getTokenKey(request,CacheEnum.GOOGLE),Consts.SUCCESS,1,TimeUnit.DAYS);
        return Result.ok();
    }


}

GoogleAuthenticator

  • Google身份驗證器工具類
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.apache.commons.codec.binary.Base32;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class GoogleAuthenticator {
	public static String getRandomSecretKey() {
		SecureRandom random = new SecureRandom();
		byte[] bytes = new byte[20];
		random.nextBytes(bytes);
		Base32 base32 = new Base32();
		String secretKey = base32.encodeToString(bytes);
		// make the secret key more human-readable by lower-casing and
		// inserting spaces between each group of 4 characters
		return secretKey.toUpperCase(); // .replaceAll("(.{4})(?=.{4})", "$1 ");
	}

	public static String getTOTPCode(String secretKey) {
		String normalizedBase32Key = secretKey.replace(" ", "").toUpperCase();
		Base32 base32 = new Base32();
		byte[] bytes = base32.decode(normalizedBase32Key);
		String hexKey = Hex.encodeHexString(bytes);
		long time = (System.currentTimeMillis() / 1000) / 30;
		String hexTime = Long.toHexString(time);
		return TOTP.generateTOTP(hexKey, hexTime, "6");
	}

	public static String getGoogleAuthenticatorBarCode(String secretKey,
			String account, String issuer) {
		String normalizedBase32Key = secretKey.replace(" ", "").toUpperCase();
		try {
			return "otpauth://totp/"
					+ URLEncoder.encode(issuer + ":" + account, "UTF-8")
							.replace("+", "%20")
					+ "?secret="
					+ URLEncoder.encode(normalizedBase32Key, "UTF-8").replace(
							"+", "%20") + "&issuer="
					+ URLEncoder.encode(issuer, "UTF-8").replace("+", "%20");
		} catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(e);
		}
	}

	public static void createQRCode(String barCodeData, String filePath,
			int height, int width) throws WriterException, IOException {
		BitMatrix matrix = new MultiFormatWriter().encode(barCodeData,
				BarcodeFormat.QR_CODE, width, height);
		try (FileOutputStream out = new FileOutputStream(filePath)) {
			MatrixToImageWriter.writeToStream(matrix, "png", out);
		}
	}

	static int window_size = 3; // default 3 - max 17 (from google docs)最多可偏移的時間

	/**
	 * set the windows size. This is an integer value representing the number of
	 * 30 second windows we allow The bigger the window, the more tolerant of
	 * clock skew we are.
	 * 
	 * @param s
	 *            window size - must be >=1 and <=17. Other values are ignored
	 */
	public static void setWindowSize(int s) {
		if (s >= 1 && s <= 17)
			window_size = s;
	}

	/**
	 * Check the code entered by the user to see if it is valid
	 * 
	 * @param secret
	 *            The users secret.
	 * @param code
	 *            The code displayed on the users device
	 * @param timeMsec
	 *            The time in msec (System.currentTimeMillis() for example)
	 * @return
	 */
	public static boolean check_code(String secret, long code, long timeMsec) {
		Base32 codec = new Base32();
		byte[] decodedKey = codec.decode(secret);
		// convert unix msec time into a 30 second "window"
		// this is per the TOTP spec (see the RFC for details)
		long t = (timeMsec / 1000L) / 30L;
		// Window is used to check codes generated in the near past.
		// You can use this value to tune how far you're willing to go.
		for (int i = -window_size; i <= window_size; ++i) {
			long hash;
			try {
				hash = verify_code(decodedKey, t + i);
			} catch (Exception e) {
				// Yes, this is bad form - but
				// the exceptions thrown would be rare and a static
				// configuration problem
				// e.printStackTrace();
				throw new RuntimeException(e.getMessage());
				// return false;
			}
			if (hash == code) {
				return true;
			}
		}
		// The validation code is invalid.
		return false;
	}

	private static int verify_code(byte[] key, long t)
			throws NoSuchAlgorithmException, InvalidKeyException {
		byte[] data = new byte[8];
		long value = t;
		for (int i = 8; i-- > 0; value >>>= 8) {
			data[i] = (byte) value;
		}
		SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
		Mac mac = Mac.getInstance("HmacSHA1");
		mac.init(signKey);
		byte[] hash = mac.doFinal(data);
		int offset = hash[20 - 1] & 0xF;
		// We're using a long because Java hasn't got unsigned int.
		long truncatedHash = 0;
		for (int i = 0; i < 4; ++i) {
			truncatedHash <<= 8;
			// We are dealing with signed bytes:
			// we just keep the first byte.
			truncatedHash |= (hash[offset + i] & 0xFF);
		}
		truncatedHash &= 0x7FFFFFFF;
		truncatedHash %= 1000000;
		return (int) truncatedHash;
	}
}

代碼地址


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM