1. 程式人生 > >電商平臺-Java後端生成Token架構與設計詳解

電商平臺-Java後端生成Token架構與設計詳解

目的:Java開源生鮮電商平臺-Java後端生成Token目的是為了用於校驗客戶端,防止重複提交.

技術選型:用開源的JWT架構。

 

1.概述:在web專案中,服務端和前端經常需要互動資料,有的時候由於網路相應慢,客戶端在提交某些敏感資料(比如按照正常的業務邏輯,此份資料只能儲存一份)時,如果前端多次點選提交按鈕會導致提交多份資料,這種情況我們是要防止發生的。

2.解決方法:

①前端處理:在提交之後通過js立即將按鈕隱藏或者置為不可用。

②後端處理:對於每次提交到後臺的資料必須校驗,也就是通過前端攜帶的令牌(一串唯一字串)與後端校驗來判斷當前資料是否有效。

3.總結:第一種方法相對來說比較簡單,但是安全係數不高,第二種方法從根本上解決了問題,所以我推薦第二種方法。

4.核心程式碼:

生成Token的工具類:

  1. /**  
  2.  * 生成Token的工具類:  
  3.  */  
  4. package red.hearing.eval.modules.token;  
  5.   
  6. import java.security.MessageDigest;  
  7. import java.security.NoSuchAlgorithmException;  
  8. import java.util.Random;  
  9.   
  10. import sun.misc.BASE64Encoder;  
  11.   
  12. /**  
  13.  * 生成Token的工具類  
  14.  * @author zhous  
  15.  * @since 2018-2-23 13:59:27  
  16.  *  
  17.  */  
  18. public class TokenProccessor {  
  19.       
  20.      private TokenProccessor(){};  
  21.      private static final TokenProccessor instance = new TokenProccessor();  
  22.        
  23.     public static TokenProccessor getInstance() {  
  24.         return instance;  
  25.     }  
  26.   
  27.     /**  
  28.      * 生成Token  
  29.      * @return  
  30.      */  
  31.     public String makeToken() {  
  32.         String token = (System.currentTimeMillis() + new Random().nextInt(999999999)) + "";  
  33.          try {  
  34.             MessageDigest md = MessageDigest.getInstance("md5");  
  35.             byte md5[] =  md.digest(token.getBytes());  
  36.             BASE64Encoder encoder = new BASE64Encoder();  
  37.             return encoder.encode(md5);  
  38.         } catch (NoSuchAlgorithmException e) {  
  39.             // TODO Auto-generated catch block  
  40.             e.printStackTrace();  
  41.         }  
  42.          return null;  
  43.     }  
  44. }  

Token通用工具類

 
  1. /**  
  2.  *   
  3.  */  
  4. package red.hearing.eval.modules.token;  
  5.   
  6. import javax.servlet.http.HttpServletRequest;  
  7.   
  8. import org.apache.commons.lang3.StringUtils;  
  9.   
  10. /**  
  11.  * Token的工具類  
  12.  * @author zhous  
  13.  * @since 2018-2-23 14:01:41  
  14.  *  
  15.  */  
  16. public class TokenTools {  
  17.       
  18.     /**  
  19.      * 生成token放入session  
  20.      * @param request  
  21.      * @param tokenServerkey  
  22.      */  
  23.     public static void createToken(HttpServletRequest request,String tokenServerkey){  
  24.         String token = TokenProccessor.getInstance().makeToken();  
  25.         request.getSession().setAttribute(tokenServerkey, token);  
  26.     }  
  27.       
  28.     /**  
  29.      * 移除token  
  30.      * @param request  
  31.      * @param tokenServerkey  
  32.      */  
  33.     public static void removeToken(HttpServletRequest request,String tokenServerkey){  
  34.         request.getSession().removeAttribute(tokenServerkey);  
  35.     }  
  36.       
  37.     /**  
  38.      * 判斷請求引數中的token是否和session中一致  
  39.      * @param request  
  40.      * @param tokenClientkey  
  41.      * @param tokenServerkey  
  42.      * @return  
  43.      */  
  44.     public static boolean judgeTokenIsEqual(HttpServletRequest request,String tokenClientkey,String tokenServerkey){  
  45.         String token_client = request.getParameter(tokenClientkey);  
  46.         if(StringUtils.isEmpty(token_client)){  
  47.             return false;  
  48.         }  
  49.         String token_server = (String) request.getSession().getAttribute(tokenServerkey);  
  50.         if(StringUtils.isEmpty(token_server)){  
  51.             return false;  
  52.         }  
  53.           
  54.         if(!token_server.equals(token_client)){  
  55.             return false;  
  56.         }  
  57.           
  58.         return true;  
  59.     }  
  60.       
  61. }  

使用方法:

①在輸出前端頁面的時候呼叫TokenTools.createToken方法,會把本次生成的token放入session中。

②然後在前端頁面提交資料時從session中獲取token,然後新增到要提交的資料中。

③服務端接受資料後呼叫judgeTokenIsEqual方法判斷兩個token是否一致,如果不一致則返回,不進行處理。

備註:tokenClientkey和tokenServerkey自定義,呼叫judgeTokenIsEqual方法時的tokenClientkey一定要與前端頁面的key一致。

 

基於微信原理JAVA實現執行緒安全Token驗證-JWT,如果不清楚JWT TOKEN的原理機制,我的上一篇JWT-TOKEN部落格有詳細介紹,這篇博文主要是具體實現。

Token主要是用於以作客戶端進行請求的一個令牌,當第一次登入後,伺服器生成一個Token便將此Token返回給客戶端,以後客戶端只需帶上這個Token前來請求資料即可,無需再次帶上密匙。

 

 

package com.franz.websocket;
 
import com.franz.common.utils.StringUtils;
import com.franz.weixin.p3.oauth2.util.MD5Util;
import io.jsonwebtoken.*;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.jeecgframework.core.common.service.CommonService;
 
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
 
 
/**
 * OAuthTokenUtils
 * Token管理
 * @author [email protected]
 * @version 2017-08-01
 */
public class OAuthTokenManager {
    private String APP_ID = "";
    private String APP_SECRET = "";
    private String KEY_SING =  ""; //用於存放TOKEN的標誌,Redis
    private LinkedHashMap<string, object=""> pairs = new LinkedHashMap();//封裝json的map
    private CommonService service;
    public static final int MINUTE_TTL = 60*1000;  //millisecond
    public static final int HOURS_TTL = 60*60*1000;  //millisecond
    public static final int DAY_TTL = 12*60*60*1000;  //millisecond
 
 
 
    private OAuthTokenManager() {}
    private static OAuthTokenManager single=null;
    public static OAuthTokenManager getInstance() {
            if (single == null) {
                single = new OAuthTokenManager();
            }
            return single;
        }
 
    public String getKEY_SING() {
        return KEY_SING;
    }
 
    public void setPairs(LinkedHashMap<string, object=""> pairs) {
        this.pairs = pairs;
    }
    public LinkedHashMap<string, object=""> getPairs() {
        return pairs;
    }
 
    public void put(String key, Object value){//向json中新增屬性,在js中訪問,請呼叫data.map.key
        pairs.put(key, value);
    }
 
    public void remove(String key){
        pairs.remove(key);
    }
 
    /**
     * 總體封裝
     * @param appid
     * @param secret
     * @param logicInterface 回撥函式
     * @return
     */
    public String token(String appid,String secret,LogicInterface logicInterface){
        //獲取appid和secret
        this.accessPairs(appid,secret);
        //驗證appid和secretS,獲取物件載體
        Object subject = this.loginAuthentication(logicInterface);
        //生成JWT簽名資料ToKen
        String token = this.createToken(this.generalSubject(subject),this.MINUTE_TTL);
        return token;
    }
 
    public void accessPairs(String APP_ID, String APP_SECRET) {
        this.APP_ID = APP_ID;
        this.APP_SECRET = APP_SECRET;
        //this.KEY_SING = MD5Util.MD5Encode(APP_ID+"_"+APP_SECRET, "UTF-8").toUpperCase();//要用到的時候才用
    }
 
    public Object loginAuthentication(LogicInterface logicInterface){
        if (StringUtils.isNotBlank(APP_ID) && StringUtils.isNotBlank(APP_SECRET)) {
                Map<string, object=""> map = new HashMap<>();
                map.put("APP_ID",APP_ID);
                map.put("APP_SECRET",APP_SECRET);
                if(logicInterface == null || logicInterface.handler(map) == null){
                    return map;
                }else {
                    return logicInterface.handler(map);
                }
        } else {
            return null;
        }
    }
    /**
     * 由字串生成加密key
     * @return
     */
    public SecretKey generalKey(){
        String stringKey = APP_ID+APP_SECRET;
        byte[] encodedKey = Base64.decodeBase64(stringKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }
    /**
     * 生成subject資訊
     * @param obj
     * @return
     */
    public static String generalSubject(Object obj){
        if(obj != null ) {
            JSONObject json = JSONObject.fromObject(obj);
            return json.toString();
        }else{
            return "{}";
        }
 
    }
 
    /**
     * 建立token
     * @param subject
     * @param ttlMillis
     * @return
     * @throws Exception
     */
    public String createToken(String subject, long ttlMillis) {
 
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(APP_ID)
                .setIssuedAt(now)
                .setSubject(subject)
                .signWith(signatureAlgorithm, key);
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }
        return builder.compact();
    }
 
    /**
     * 解密token
     * @param token
     * @return
     * @throws Exception
     */
    public Claims validateToken(String token) throws Exception{
        Claims claims = Jwts.parser()
                .setSigningKey(generalKey())
                .parseClaimsJws(token).getBody();
        /*System.out.println("ID: " + claims.getId());
        System.out.println("Subject: " + claims.getSubject());
        System.out.println("Issuer: " + claims.getIssuer());
        System.out.println("Expiration: " + claims.getExpiration());*/
        return claims;
    }
}
import com.ewider.weixin.p3.oauth2.util.MD5Util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
 
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
/**
 * OAuthTokenController
 *
 * @author Franz.ge.倪志耿
 * @version 2017-08-01
 */
@Scope("prototype")
@Controller
@RequestMapping("/oAuthToken")
public class OAuthToken {
 
    /**
     * 獲取Token
     * @param grant_type
     * @param appid
     * @param secret
     * @return
     */
    @RequestMapping(params = "token",method = RequestMethod.GET)
    @ResponseBody
    public Object token (@RequestParam(value = "grant_type") String grant_type, @RequestParam(value = "appid") String appid,
            @RequestParam(value = "secret") String secret,HttpServletResponse response) {
        Map<string, object=""> map = new HashMap<>();
        switch (grant_type) {
            case "authorization_code" : //授權碼模式(即先登入獲取code,再獲取token)
                break;
            case "password" : //密碼模式(將使用者名稱,密碼傳過去,直接獲取token)
                break;
            case "client_credentials" : //客戶端模式(無使用者,使用者向客戶端註冊,然後客戶端以自己的名義向’服務端’獲取資源)
                OAuthTokenManager oAuthTokenManager = OAuthTokenManager.getInstance();
                String token = oAuthTokenManager.token(appid, secret,null);//loginInterface是業務邏輯回掉函式
                //返回Token
                map.put("access_token",token);
                map.put("expires_in",OAuthTokenManager.MINUTE_TTL/1000);
                break;
            case "implicit" : //簡化模式(在redirect_uri 的Hash傳遞token; Auth客戶端執行在瀏覽器中,如JS,Flash)
                break;
            case "refresh_token" : //重新整理access_token
                break;
        }
 
        return map;
    }
 
    @RequestMapping(params = "loginAuth2",method = RequestMethod.GET)
    @ResponseBody
    public Object loginAuth2 (HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "accessToken") String accessToken ){
        Map<string, object=""> map = new HashMap<>();
        //COOKIE不存在:解析驗證正確性
        try {
                OAuthTokenManager oAuthTokenManager = OAuthTokenManager.getInstance();
                Claims claims = oAuthTokenManager.validateToken(accessToken);
                if (claims != null ) {
                    map.put("state","success");
                    map.put("loginAuth","採用Token登入");
                    int validMillis = (int)(claims.getExpiration().getTime()-System.currentTimeMillis());
                    if(validMillis > 0) {
                        //交給容器管理,可以存放redis,這裡模擬是cookie
                        Cookie cookie = new Cookie(MD5Util.MD5Encode("MD5SING", "UTF-8").toUpperCase(), accessToken);
                        cookie.setMaxAge(validMillis/1000);
                        response.addCookie(cookie);
                    }
 
                }else{
                    map.put("state","fail");
                }
            }catch (MalformedJwtException | SignatureException e){
                     map.put("state","signature");//改造簽名,或者無效的Token
                     map.put("loginAuth","該Token無效");//改造簽名,或者無效的Token
            }catch (ExpiredJwtException e){
                     map.put("state","expired");//改造簽名,或者無效的Token
                     map.put("loginAuth","Token已經過時");
            }catch (Exception e) {
            e.printStackTrace();
            map.put("state","fail");
            }
            return map;
    }
 
    @RequestMapping(params = "index",method = RequestMethod.GET)
    @ResponseBody
    public Object index (HttpServletRequest request, HttpServletResponse response){
        Map<string, object=""> map = new HashMap<>();
        //從COOKIE中查詢,模擬訪問,可以整合容器管理
        Cookie[] cookies = request.getCookies();
        if (cookies!=null) {
            for (int i = cookies.length-1; i >= 0; i--) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(MD5Util.MD5Encode("MD5SING", "UTF-8").toUpperCase())) {
                    //跳過登陸
                    map.put("index","採用Redis登入");
                    return map;
                }
            }
        }
        map.put("index","你的Token已經銷燬");
        return map;
    }
 
}
        <dependency>
            <groupid>io.jsonwebtoken</groupid>
           <artifactid>jjwt</artifactid>
            <version>0.7.0</version>
        </dependency>