java中怎么实现动态口令登录
创始人
2024-12-21 22:21:54
0次

1.实现一个ItsClient 客户端用来实例化调用验证功能

public class ItsClient {private static final String routing = "/v1.0/sectoken/otp_validation";// ! HTTPS消息验证地址private String httpsVerifyUrl = "";// ! otp ipAddrprivate String ipAddr = "";// ! otp portprivate String port = "";// ! otp appIDprivate String appID = "";// ! otp appKeyprivate String appKey = "";// ! 错误码private int errorCode = 0;// ! 错误消息private String errorMessage = "";TreeMap errorCodeTable = new TreeMap() {{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 String 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 map) {JSONObject jmap = new JSONObject(map);return jmap.toString();}public TreeMap DecodeJson(String jsonStr) throws ParseException {JSONObject jsonObject = new JSONObject(jsonStr);TreeMap retMap = new TreeMap();Iterator 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 params) {String queryStr = "";Iterator 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 params = new TreeMap() {{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 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服务的AppIDprivate static String otpAppID = "";// OTP服务的AppKeyprivate 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)){//认证成功,跳转页面}

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...