In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "detailed explanation of token problems after layui login". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Layui is a very simple and practical background management system framework, in which plug-ins are rich and easy to use, and only need to be modified on the original basis, but it is slightly weak in data processing, and the built-in jquery is slightly insufficient in the actual process. It would be better if you can add a built-in mvc schema framework.
Let's first introduce the use of layui in login.
The login problem mainly lies in the storage call of token, which first posts the code of creating token and interceptor in the background.
First introduce the jar package
Io.jsonwebtoken jjwt 0.7.0 jackson-databind com.fasterxml.jackson.core
Token uses io.jsonwebtoken to customize the key and store login information
Package com.zeus.utils;import cn.hutool.json.JSON;import cn.hutool.json.JSONObject;import cn.hutool.json.JSONUtil;import com.zeus.constant.CommonConstants;import io.jsonwebtoken.Claims;import io.jsonwebtoken.JwtBuilder;import io.jsonwebtoken.Jwts;import io.jsonwebtoken.SignatureAlgorithm;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import javax.crypto.spec.SecretKeySpec;import javax.xml.bind.DatatypeConverter;import java.security.Key;import java.util.Date Public class TokenUtil {private static Logger LOG = LoggerFactory.getLogger (TokenUtil.class); / * * create TOKEN * * @ param id, issuer, subject, ttlMillis * @ return java.lang.String * @ methodName createJWT * @ author fusheng * @ date 2019-1-10 * / public static String createJWT (String id, String issuer, String subject, long ttlMillis) {SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256 Long nowMillis = System.currentTimeMillis (); Date now = new Date (nowMillis); byte [] apiKeySecretBytes = DatatypeConverter.parseBase64Binary ("englishlearningwebsite"); Key signingKey = new SecretKeySpec (apiKeySecretBytes, signatureAlgorithm.getJcaName ()) JwtBuilder builder = Jwts.builder (). SetId (id) .setIssuedAt (now) .setSubject (subject) .setIssuer (issuer) .signWith (signatureAlgorithm, signingKey); if (ttlMillis > = 0) {long expMillis = nowMillis + ttlMillis; Date exp = new Date (expMillis); builder.setExpiration (exp) } return builder.compact () } / * * decrypt TOKEN * * @ param jwt * @ return io.jsonwebtoken.Claims * @ methodName parseJWT * @ author fusheng * @ date 2019-1-10 * / public static Claims parseJWT (String jwt) {Claims claims = Jwts.parser () .setSigningKey (DatatypeConverter.parseBase64Binary ("englishlearningwebsite")) .parseClaimsJws (jwt). GetBody () Return claims;}}
ParseJWT method is mainly used in decryption.
Public static Contact getContact (String token) {Claims claims = null; Contact contact = null; if (token! = null) {/ / get claims class claims = TokenUtil.parseJWT (token); cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj (claims.getSubject ()); contact = jsonObject.get ("user", Contact.class);} return contact;}
Claims is the decrypted token class, which stores all the information in token.
/ / decrypt token claims = TokenUtil.parseJWT (token); / / get the user's type String issuer = claims.getIssuer (); / / get the login time Date issuedAt = claims.getIssuedAt (); / / get the set login id String id = claims.getId () / / claims.getExpiration (). GetTime () > DateUtil.date (). GetTime () to determine whether the tokern has expired / / get the object stored in token cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj (claims.getSubject ()); Contact contact = jsonObject.get ("user", Contact.class)
The created token is placed in the request header in the page, and the backend uses the interceptor to determine whether it expires. If it expires, the request is intercepted. If successful, the new token update expiration time is returned in the response header.
Package com.zeus.interceptor;import cn.hutool.core.date.DateUtil;import cn.hutool.json.JSON;import cn.hutool.json.JSONUtil;import com.zeus.utils.TokenUtil;import io.jsonwebtoken.Claims;import org.apache.commons.lang.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter Import java.util.Map;import static com.zeus.constant.CommonConstants.EFFECTIVE_TIME;/** * login interceptor * * @ author:fusheng * @ date:2019/1/10 * @ ver:1.0 * * / public class LoginHandlerIntercepter implements HandlerInterceptor {private static final Logger LOG = LoggerFactory.getLogger (LoginHandlerIntercepter.class) / * * token check * * @ param httpServletRequest, httpServletResponse, o * @ return boolean * @ methodName preHandle * @ date 2019-1-3 0003 * / @ Override public boolean preHandle (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {Map mapIn = httpServletRequest.getParameterMap (); JSON jsonObject = JSONUtil.parseObj (mapIn); StringBuffer stringBuffer = httpServletRequest.getRequestURL () LOG.info ("httpServletRequest, path:" + stringBuffer + "; input parameters:" + JSONUtil.toJsonStr (jsonObject)); / / verify the login status of APP, if token does not expire LOG.info ("come in preHandle"); String oldToken = httpServletRequest.getHeader ("token"); LOG.info ("token:" + oldToken) / * refresh token and extend the validity period to one month * / if (StringUtils.isNotBlank (oldToken)) {Claims claims = null; try {claims = TokenUtil.parseJWT (oldToken);} catch (Exception e) {e.printStackTrace () String str = "{\" code\ ": 801,\" msg\ ":\" login fails, please log in again\ "}"; dealErrorReturn (httpServletRequest, httpServletResponse, str); return false;} if (claims.getExpiration (). GetTime () > DateUtil.date (). GetTime ()) {String userId = claims.getId () Try {String newToken = TokenUtil.createJWT (claims.getId (), claims.getIssuer (), claims.getSubject (), EFFECTIVE_TIME); LOG.info ("new TOKEN: {}", newToken); httpServletRequest.setAttribute ("userId", userId); httpServletResponse.setHeader ("token", newToken) LOG.info ("flush token success, {}", oldToken); return true;} catch (Exception e) {e.printStackTrace (); String str = "{\" code\ ": 801,\" msg\ ":\" login is invalid, please log in again\ "}" DealErrorReturn (httpServletRequest, httpServletResponse, str); return false;} String str = "{\" code\ ": 801,\" msg\ ":\" login fails, please log in again\ "}"; dealErrorReturn (httpServletRequest, httpServletResponse, str); return false } @ Override public void postHandle (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {} @ Override public void afterCompletion (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {} / * return error message to WEB * * @ param httpServletRequest, httpServletResponse Obj * @ return void * @ methodName dealErrorReturn * @ author fusheng * @ date 2019-1-3 0003 * / public void dealErrorReturn (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object obj) {String json = (String) obj PrintWriter writer = null; httpServletResponse.setCharacterEncoding ("UTF-8"); httpServletResponse.setContentType ("application/json; charset=utf-8"); try {writer = httpServletResponse.getWriter (); writer.print (json);} catch (IOException ex) {LOG.error ("response error", ex) } finally {if (writer! = null) {writer.close ();}
After talking about token, let's talk about how layui stores token and adds token to the request header each time you render.
Form.on ('submit (LAY-user-login-submit)', function (obj) {/ / request login API admin.req ({/ / change it to server-side real API url:'/ userInfo/login', method: 'POST', data: obj.field Done: function (res) {if (res.code = 0) {/ / after the request is successful Write access_token layui.data (setter.tableName, {key: "token", value: res.data.token}) / / prompt for successful login and jump to layer.msg (res.msg, {offset: '15pxshipping, icon: 1, time: 1000}) Function () {location.href = "index"}) } else {layer.msg (res.msg, {offset: '15pxrabbit, icon: 1, time: 1000}) );})
We store the returned token information in a table stored locally by layui. The table name is configured in config.js. Generally, you can use layui.setter.tableName directly.
Since the table of layui is rendered through js, we cannot set the request header in js, and it is very troublesome to configure each table, but the data table of layui is based on the request of ajax, so we choose to manually modify the table.js in the module of layui so that every request will carry the request header automatically.
A.contentType & 0 = = a.contentType.indexOf ("application/json") & & (d = JSON.stringify (d)), t.ajax ({type: a.method | | "get", url: a.url, contentType: a.contentType, data: d, dataType: "json" Headers: {"token": layui.data (layui.setter.tableName) ['token']}, success: function (t) {if (t.code==801) {top.location.href = "index" } else {"function" = = typeof a.parseData & & (t = a.parseData (t) | | t), t [n.statusName]! = n.statusCode? (i.renderForm (), i.layMain.html (''+ (t [n.msgName]) | | "the returned data does not conform to the specification The correct success status code ("+ n.statusName +") should be: "+ n.statusCode) +")): (i.renderData (t, e, t [n.countName]), o (), a.time = (new Date). GetTime ()-i.startTime + "ms"), i.setColsWidth (), "function" = = typeof a.done & a.done (t, e) T [n.countName])}, error: function (e, t) {i.layMain.html ('data interface request exception:' + t + "), i.renderForm (), i.setColsWidth ()}, complete: function (xhr) Data) {layui.data (layui.setter.tableName, {key: "token", value: xhr.getResponseHeader ("token") = = null?layui.data (layui.setter.tableName) ['token']: xhr.getResponseHeader ("token")})})
Find this code in table.js and follow the configuration above
Headers: {"token": layui.data (layui.setter.tableName) ['token']}, here is the token that sets the request header and gets the layui.data (layui.setter.tableName) [' token'] stored in the table after a successful login, so it is easy to carry token.
At the same time, we need to update the expiration time of token, so we need to get the new token and put it in the table.
Complete: function (xhr,data) {layui.data (layui.setter.tableName, {key: "token", value: xhr.getResponseHeader ("token") = = null?layui.data (layui.setter.tableName) ['token']: xhr.getResponseHeader ("token")})}
Use the complete method of ajax to get the token and overwrite the old token of the table. If empty, it will not be overwritten.
After table, let's take a look at the request. Jquery is built into layui, and you can use var $= layui,jquery to use the built-in ajax. Then we also need to configure ajax.
Pe.extend ({active: 0, lastModified: {}, etag: {}, ajaxSettings: {url: en, type: "GET", isLocal: Vt.test (tn [1]), global:! 0, processData:! 0, async:! 0 Headers: {"token": layui.data (layui.setter.tableName) ['token']}, contentType: "application/x-www-form-urlencoded Charset=UTF-8 ", accepts: {" * ": Zt, text:" text/plain ", html:" text/html ", xml:" application/xml, text/xml ", json:" application/json, text/javascript "}, contents: {xml: /\ bxml\ b / Html: /\ bhtml/, json: /\ bjson\ b /}, responseFields: {xml: "responseXML", text: "responseText", json: "responseJSON"}, converters: {"* text": String, "text html":! 0, "text json": pe.parseJSON, "text xml": pe.parseXML}, flatOptions: {url:! 0, context:! 0}}
Also find ajaxSettings in the ayui.js or layui.all.js you reference: just configure it.
This is the end of the content of "detailed explanation of token problems after layui login". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.