java動態口令登錄實現過程詳解

這篇文章主要介紹了java動態口令登錄實現過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

1.實現一個ItsClient 客戶端用來實例化調用驗證功能

public class ItsClient {
	private static final String routing = "/v1.0/sectoken/otp_validation";
	// ! HTTPS消息驗證地址
	private String httpsVerifyUrl = "";
	// ! otp ipAddr
	private String ipAddr = "";
	// ! otp port
	private String port = "";
	// ! otp appID
	private String appID = "";
	// ! otp appKey
	private String appKey = "";
	// ! 錯誤碼
	private int errorCode = 0;
	// ! 錯誤消息
	private String errorMessage = "";
	TreeMap<Integer, String> errorCodeTable = new TreeMap<Integer, String>() {
		{
			put(200, "請求成功");
			put(400, "輸入不合法,比如請求數據不是json");
			put(401, "AppID不合法");
			put(402, "指紋不合法");
			put(410, "非法用戶,驗證otp時,傳入的uid有誤,找不到用戶");
			put(411, "錯誤的otp");
			put(412, "一個週期內動態口令只能使用一次");
			put(413, "已達一個週期內最大嘗試次數");
			put(500, "ITS服務器內部錯誤");
			put(601, "參數錯誤");
			put(602, "sha1簽名失敗");
			put(603, "操作json失敗");
			put(604, "url訪問錯誤:");
			put(605, "較驗返回指紋失敗");
		}
	};
	public ItsClient() {
		this.ipAddr = ItsConf.GetIpAddr();
		this.port = ItsConf.GetPort();
		this.appID = ItsConf.GetOtpAppID();
		this.appKey = ItsConf.GetOtpAppKey();
		httpsVerifyUrl = "https://" + this.ipAddr + ':' + this.port + routing;
	}
	 //獲取錯誤信息
	public St ring GetErrorMessage() {
		return this.errorMessage;

	}

        //獲取錯誤碼

        public int GetErrorCode() {

		return this.errorCode;
	}
	public void SetError(int errorCode, String extMessage) {
		this.errorCode = errorCode;
		this.errorMessage = this.errorCodeTable.get(this.errorCode).toString() + extMessage;
	}

	public static String SHA1(String decript) throws NoSuchAlgorithmException {
		String ret = "";
		MessageDigest sha1 = MessageDigest.getInstance("SHA1");
		byte[] sha1bytes = sha1.digest(decript.getBytes());
		if (sha1bytes != null) {
			ret = new BASE64Encoder().encode(sha1bytes);
		}
		return ret;
	}
	public String EncodeJson(TreeMap<String, String> map) {
		JSONObject jmap = new JSONObject(map);
		return jmap.toString();
	}
	public TreeMap<String, Object> DecodeJson(String jsonStr) throws ParseException {
		JSONObject jsonObject = new JSONObject(jsonStr);
		TreeMap<String, Object> retMap = new TreeMap<String, Object>();
		Iterator<String> iter = jsonObject.keys();
		String key = null;
		Object value = null;
		while (iter.hasNext()) {
			key = iter.next();
			value = jsonObject.get(key);
			retMap.put(key, value);
		}
		return retMap;
	}
	public String BuildQueryStr(TreeMap<String, String> params) {
		String queryStr = "";
		Iterator<String> itr = params.keySet().iterator();
		while (itr.hasNext()) {
			String key = itr.next();
			queryStr += (key + "=" + params.get(key).toString() + "&");
		}
		return queryStr.substring(0, queryStr.length() - 1);
	}
	public boolean IsEmptyOrNull(String param) {
		return param == null || param.length() <= 0;
	}
	/**
	 * @brief 驗證otp
	 * @param uid ITS主賬號UID或已配置的從賬號
	 * @param otp 需要驗證的動態口令
	 * @return bool true: 成功, false: 失敗
	 */
	@SuppressWarnings("serial")
	public boolean AuthOtp(final String uid, final String otp) {
		if (IsEmptyOrNull(this.ipAddr) || IsEmptyOrNull(this.port) || IsEmptyOrNull(this.appID)
				|| IsEmptyOrNull(this.appKey) || IsEmptyOrNull(uid) || IsEmptyOrNull(otp)) {
			SetError(601, "");
			return false;
		}
		TreeMap<String, String> params = new TreeMap<String, String>() {
			{
				put("app_id", appID);
				put("app_key", appKey);
				put("uid", uid);
				put("otp", otp);
			}
		};
		String qureyStr = this.BuildQueryStr(params);
		String fingerprint = "";
		try {
			fingerprint = SHA1(qureyStr);
		} catch (Exception ex) {
			ex.printStackTrace();
			SetError(602, ex.getMessage());
			return false;
		}
		params.remove("app_key");
		params.put("fingerprint", fingerprint);
		String postStr = "";
		try {
			postStr = EncodeJson(params);
		} catch (Exception ex) {
			ex.printStackTrace();
			SetError(603, "json encode" + ex.getMessage());
			return false;
		}
		HttpsClient conn = null;
		String res = "";
		try {
			conn = new HttpsClient();
			res = conn.post(this.httpsVerifyUrl, postStr); // 訪問接口調取返回結果
		} catch (Exception ex) {
			ex.printStackTrace();
			SetError(604, ex.getMessage());
			return false;
		}
		TreeMap<String, Object> ret = null;
		try {
			ret = DecodeJson(res);
		} catch (Exception ex) {
			ex.printStackTrace();
			SetError(603, "json decode " + ex.getMessage());
			return false;
		}
		int retCode = (Integer) ret.get("status"); 
		if (200 != retCode) {
			SetError(retCode, "");
			return false;
		}
		return true;
	}
}

2.實現一個HttpsClient 請求工具

public class HttpsClient {
    final static HostnameVerifier doNotVerifier = new HostnameVerifier() {  
        public boolean verify(String hostname, SSLSession session) {  
            return true;
        }
    };
    /** 
     * @brief 發送請求 
     * @param httpsUrl 請求的地址 
     * @param postStr 請求的數據 
     * @throws Exception 
     */  
    public String post(String httpsUrl, String postStr) throws Exception {  
        HttpsURLConnection conn = null;
        StringBuffer recvBuff = new StringBuffer();  
        String resData = ""; 
        try {
            conn = (HttpsURLConnection) (new URL(httpsUrl)).openConnection();  
            conn.setHostnameVerifier(doNotVerifier);
            conn.setDoInput(true);  
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", " application/json");
            conn.setRequestProperty("Content-Length", String.valueOf(postStr.getBytes("utf-8").length));  
            conn.setUseCaches(false);
            //設置爲utf-8可以解決服務器接收時讀取的數據中文亂碼問題  
            conn.getOutputStream().write(postStr.getBytes("utf-8"));  
            conn.getOutputStream().flush();  
            conn.getOutputStream().close();  
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));  
            String line;
            while ((line = in.readLine()) != null) {  
                recvBuff.append(line);  
            } 
            resData = recvBuff.toString();
            return resData;
        } catch (MalformedURLException ex) {
             throw ex;  
        } catch (IOException ex) {  
             throw ex;  
        } catch (Exception ex) {  
             throw ex;  
        }  
    } 
}

3.實現Its一個配置用來配置Its服務器信息接口訪問地址

public class ItsConf {
	// ITS服務器地址 1.1.1.1 或 xxx.xxx.com的形式
	private static String ipAddr = "";
	// ITS服務器端口
	private static String port = "";
	// OTP服務的AppID
	private static String otpAppID = "";
	// OTP服務的AppKey
	private static String otpAppKey = "";
	public static String GetIpAddr() {
		return ipAddr;
	}
	public static String GetPort() {
		return port;
	}
	public static String GetOtpAppID() {
		return otpAppID;
	}
	public static String GetOtpAppKey() {
		return otpAppKey;
	}
}

4.接下來就是LoginContorller 完成口令認證

//username 用戶名
//code動態口令密碼
ItsClient itsClient = new ItsClient();
if(itsClient.AuthOtp(username, code)){
	//認證成功,跳轉頁面
}

5.登陸頁面就省略了,自己完成吧

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章