Article introduction
Project A jumps to project B. when project A logs in as, it also needs to enter the account of project B when logging in to project B. the user experience is not good. Therefore, the two items need to be bound. After logging in to item A, you can log in directly when jumping to item b. This project is to maintain other people's old systems and is developed using jsp. Although the technology used is relatively old, the idea of the whole process is still very good.
Business process analysis
- Carry ticket when item A jumps to item B
- After item B obtains the ticket, it parses the user information
- Judge whether the user exists in the database according to the user information. If so, return to the front end and directly log in to item B status. If not saved, it will be inserted, and if there is an error, it will return to the front-end item B status that cannot be logged in directly
- The session is used to save user status, because it is a jsp project and the technology is relatively old.
- The front end jumps according to the status. If it succeeds, it redirects the system home page, and if it fails, it stays on the login page.
Get the ticket and parse it
From project A to project B, the original system jumps to the login page. Here I encapsulate A method. When the login page of project B is loaded, call the back-end method to parse the ticket.
After the ticket is obtained, the appid, secret and ticket are registered in MD5
After encrypting, the signature is formed, and then the third party interface is called to get the user's information.
Verify the ticket interface
@ResponseBody @RequestMapping(value = "/login/verify", method = {RequestMethod.GET}) public boolean verifySignature(HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException { logger.info("check signature"); String ticket = request.getParameter("ticket").replace("ticket=", ""); String secret = "2nN5Dd+Ehz9mJ0XXXXXXXXXXXXXX4="; String appId = "188883"; String pass = ticket + appId + secret; String signature = encodeMd5(pass); //TODO calls the third-party interface String url = "http://www.XXXX.com/open/api/v10/token?" + "ticket=" + ticket + "&appid=" + appId + "&signature=" + signature; System.out.println(url); JSONObject currentUserResult = sendRequest(url); String un = currentUserResult.getString("un"); String dis = currentUserResult.getString("dis"); String contextPath = request.getContextPath(); //If the user exists, the user is returned; if it does not exist, null is returned AdminEntity adminEntity = adminService.existAdminNameAndReturnAdmin(un); if (adminEntity != null) { httpSession.setAttribute("admin", adminEntity); return true; } else { //The default password for creating a user is 123456 adminEntity = new AdminEntity(); adminEntity.setNickname(un); adminEntity.setPhoneNumber(""); adminEntity.setEmail(""); adminEntity.setCompany(""); adminEntity.setSex(1); adminEntity.setRole(1); adminEntity.setVisible(1); adminEntity.setPassword("123456"); //The database does not exist for insertion int status = adminService.register(adminEntity); if (status > 0) { //Login free succeeded //Record the user's login status through session httpSession.setAttribute("admin", adminEntity); return true; } else { return false; } } }
Send third party request encapsulation
Redirect and jump according to the verification results. If the verification is successful, jump to system B. if the verification fails, jump to the login page of system B.
public JSONObject sendRequest(String url) { HttpURLConnection conn = null; try { URL serverUrl = new URL(url); conn = (HttpURLConnection) serverUrl.openConnection(); conn.setRequestMethod("GET"); //Set the connection timeout and read timeout conn.setConnectTimeout(15000); conn.setReadTimeout(60000); conn.setRequestProperty("Accept", "application/json"); //false must be set, otherwise it will automatically redirect to the backward address conn.setInstanceFollowRedirects(false); //Send request conn.connect(); } catch (Exception e) { e.printStackTrace(); } //Get return value return getHttpReturn(conn); } //Get request return value public JSONObject getHttpReturn(HttpURLConnection connection) { //Converts the returned input stream to a string BufferedReader bufferedReader = null; InputStreamReader inputStreamReader = null; String result = ""; try { if (200 == connection.getResponseCode()) { StringBuffer buffer = new StringBuffer(); inputStreamReader = new InputStreamReader(connection.getInputStream(), "UTF-8"); bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } result = buffer.toString(); } else { System.out.println("ResponseCode is an error code:" + connection.getResponseCode()); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (inputStreamReader != null) { inputStreamReader.close(); } if (bufferedReader != null) { bufferedReader.close(); } } catch (IOException e) { e.printStackTrace(); } connection.disconnect(); } JSONObject res = new JSONObject(result); logger.info("[obtain signature]"+res); return res; }
MD5 encryption
32-bit uppercase encryption
public String encodeMd5(String pass) throws NoSuchAlgorithmException, UnsupportedEncodingException { //md5 uppercase encryption MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update((pass).getBytes("UTF-8")); byte b[] = md5.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } return buf.toString().toUpperCase(); }
Front page Jump
In fact, the initial implementation scheme is that the checksum jump is completed in an interface. The interface directly returns the string of the corresponding page for page redirection. However, ajax does not support page redirection and only supports page refresh. In this way, although the back end indicates redirection, it actually stays on the original page, so the verified page is separated.
window.onload = function () { var ticket = getUrlParams(window.location.href, "ticket"); var basePath=$('#basePath').attr("value"); var path=$('#path').attr("value"); console.log("path"+path) console.log("bathPath"+basePath) if (ticket != null && ticket != "") { $.ajax({ //Verify target url: path+"/login/verify?ticket=" + ticket, type: "GET",//Request mode //Parameter setting // data:"username=tom&age=18", Callback function after successful response data: {}, //Request succeeded success: function (data) { console.log(data) if (data == true) { window.location.href = basePath+"/login/avoidLogin"; } else { window.location.href = basePath; } }, //request was aborted error: function () { window.location.href = basePath; }, //Format the received response data dateType: "text" }) } };
Get the current request address in jsp
<basePath value = "<%=path%>" id = "path"></basePath> var path=$('#path').attr("value");
jsp to get the current request path
<basePath value = "<%=basePath%>" id = "basePath"></basePath> var basePath=$('#basePath').attr("value");
js to get the current url address
window.location.href
js gets the parameters in the request path
var ticket = getUrlParams(window.location.href, "ticket"); function getUrlParams(url, name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)") const cuturl = url.substr(url.indexOf("?") + 1) const matchArray = cuturl.match(reg) if (matchArray) { return decodeURI(matchArray[2]) } return null; };
After successful verification, login free processing is required
Because when we request the interface again, we use js redirection instead of sending ajax requests, so we can directly redirect to the specified page through the return string on the back end.
@RequestMapping(value = "/login/avoidLogin", method = {RequestMethod.GET}) public String avoidLogin(HttpServletRequest request, HttpServletResponse response, final RedirectAttributes redirectAttributes, Model model) throws Exception { logger.info("Login free"); AdminEntity admin = (AdminEntity) httpSession.getAttribute("admin"); String contextPath = request.getContextPath(); if (admin != null) { //Log in successfully and jump to the home page. redirectAttributes.addFlashAttribute("css", "success"); redirectAttributes.addFlashAttribute("msg", "Login succeeded!"); if (admin.getRole() == Constants.USER) {//Ordinary users //model.addAttribute("to", "adminDetail"); model.addAttribute("to", "myproject"); } else if (admin.getRole() == Constants.SUPERADMIN || admin.getRole() == Constants.ADMIN) {//General administrator, system administrator //model.addAttribute("to", "adminList"); model.addAttribute("to", "myproject"); } return "manager/index";//Jump to the background home page } else { if (LoginInterceptor.verifyCert(request) == false) { System.out.println("certFlag: The certificate is invalid"); response.sendRedirect(contextPath + "/cert.jsp"); } else { System.out.println("certFlag: Certificate valid"); } return "manager/homepage"; } // } }