1. 程式人生 > 其它 >【JavaWeb】 介面鑑權

【JavaWeb】 介面鑑權

 

一年前寫過一篇,叫Webservice校驗機制,叫法不太對,就是介面鑑權

https://www.cnblogs.com/mindzone/p/15078436.html

 

這東西就是說,你提供給外部的呼叫的這個介面,並不是隨便一個請求就能訪問的,需要增加一個校驗的邏輯

只有符合這個邏輯的呼叫方才可以訪問使用你的介面,算是安全性的措施吧:

 

這篇新增加了一個更為簡單一點的,程式碼量稍微少一點的案例:

 

首先是SHA256的加密類:

package com.yonyou.dmscloud.interfaceManage.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * @Description: 實現Sha256例項 * @author: zkf * @date 2020年10月13日 */ public class Sha256 { /** * @Description: * @author: zkf * @date 2020年10月13日 * @param str 加密後的報文 * @param encoder 編碼方式(例:UTF-8) *
@return String */ public static String getSHA256(String str,String encoder) { MessageDigest messageDigest; String encodestr = ""; try { messageDigest = MessageDigest.getInstance("SHA-256"); messageDigest.update(str.getBytes(encoder)); encodestr
= byte2Hex(messageDigest.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return encodestr; } /** * 將byte轉為16進位制 * * @param bytes * @return */ private static String byte2Hex(byte[] bytes) { StringBuffer stringBuffer = new StringBuffer(); String temp = null; for (int i = 0; i < bytes.length; i++) { temp = Integer.toHexString(bytes[i] & 0xFF); if (temp.length() == 1) { // 1得到一位的進行補0操作 stringBuffer.append("0"); } stringBuffer.append(temp); } return stringBuffer.toString(); } }

 

然後是介面處理的過程:

package com.yonyou.dmscloud.interfaceManage.utils;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;


public class HttpClientJsonUtilShuZi {
    
    @Autowired
    Sha256 sha256 = new Sha256();
    
    /**
     * 數字門店鑑權欄位 key
     */
    private static final String apiKey = "4EA18E9EFB1F0EB645AD17B6BA01BA40";

    /** 
     * @Description: 1.數字門店 Aibee-Auth-Sign=sha256(Method + URL + Date + ApiSecret) 
     *                     編碼方式: UTF-8;+表示字串拼接;Date: 請求的時間戳;Method: GET/POST/PUT/DELETE
     *                     URL: 即本文件提供的介面url,不帶域名或ip、埠號(舉例:/function/updateCustomerTag)。
     *                     ApiSecret: BABBED1ABEC3277092EE0BEE96A6D740
     *                     apiKey: 4EA18E9EFB1F0EB645AD17B6BA01BA40
     * @author: zkf
     * @date 2020年10月13日
     * @param url
     * @param json
     * @param map     map.get("method");
                     map.get("url");
     * @return String 
     */
    public static String doPostJson(String url, String json,Map<String,String> map) {
        // 建立Httpclient物件
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 建立Http Post請求
            HttpPost httpPost = new HttpPost(url);

            // 建立請求內容
            StringEntity entity = new StringEntity(json, "utf-8");
            entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
            httpPost.setEntity(entity);
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            //獲得時間戳
            String timeData = getTime();
            httpPost.setHeader("Date", timeData);
            //Aibee-Auth-Sign=sha256(Method + URL + Date + ApiSecret)
            String method = map.get("method");
            String notIpUrl = map.get("url");
            String apiSecret = "BABBED1ABEC3277092EE0BEE96A6D740";
            String aibeeAuthSign = method+notIpUrl+timeData+apiSecret;

            //Sha256加密
            aibeeAuthSign = Sha256.getSHA256(aibeeAuthSign,"UTF-8");
            httpPost.setHeader("Authorization", apiKey+":"+aibeeAuthSign);
            
            // 執行http請求
            response = httpClient.execute(httpPost);
            
            //獲取結果實體
            HttpEntity entity = response.getEntity();
            
            if (entity != null) {
                //按指定編碼轉換結果實體為String型別
                resultString = EntityUtils.toString(htpEnti, "utf-8");
            }
            EntityUtils.consume(entity);
            //釋放連結
            response.close();
            return resultString;

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    /** 
     * @Description: 返回時間戳
     * @author: zkf
     * @date 2020年10月13日
     * @return String 
     */
    private static String getTime() {
        Date date = new Date();
        long time = date.getTime();
        return String.valueOf(time);//獲得時間戳
    }

}