Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use token to realize the function of verifying login in ssm

2025-04-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to use token to achieve the function of check login in ssm. The article is very detailed and has certain reference value. Interested friends must finish reading it!

Background

Token, which means "token", is a string generated by the server as an identity for the client to make the request.

When the user logs in for the first time, the server generates a token and returns the token to the client. Later, the client only needs to bring the token to request data, without the need to bring the user name and password again.

The composition of simple token; uid (unique identity of the user), time (timestamp of the current time), sign (signature, the first few bits of token are compressed into a certain length hexadecimal string by hashing algorithm. To prevent token leakage)

Working with scen

Token can also play the role of anti-crawlers, of course, crawlers also have a breakthrough way, although this can still reduce the load caused by some crawlers accessing the server. The relative threshold of crawler technology has become higher.

Using session can also achieve the purpose of user authentication, but session consumes the memory of the server. In projects with high performance requirements, this technology is outdated compared with token in development.

Supplement

Token is mainly used in the vast number of Android developers

Using interceptor in springmvc to implement

Usage

Reference the jar package in the pom.xml configuration in the maven ssm project

Com.auth0 java-jwt 3.3.0

Create a JwtUtil utility class

Package xyz.amewin.util;import com.auth0.jwt.JWT;import com.auth0.jwt.JWTVerifier;import com.auth0.jwt.algorithms.Algorithm;import com.auth0.jwt.exceptions.JWTDecodeException;import com.auth0.jwt.interfaces.DecodedJWT;import java.io.UnsupportedEncodingException;import java.util.Date;import java.util.HashMap;import java.util.Map / * Java web token tool class * * @ author qiaokun * @ date 2018-08-10 * / public class JwtUtil {/ * Expiration time is one day, * TODO is changed to 15 minutes * / private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000; / * * token private key * / private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618" / * verify that token is correct * * @ param token key * @ return is correct * / public static boolean verify (String token) {try {Algorithm algorithm = Algorithm.HMAC256 (TOKEN_SECRET); JWTVerifier verifier = JWT.require (algorithm) .build (); DecodedJWT jwt = verifier.verify (token) Return true;} catch (Exception exception) {return false;}} / * to obtain the information in token, you can obtain the user name * / public static String getUsername (String token) {try {DecodedJWT jwt = JWT.decode (token) contained in * * @ return token without secret decryption Return jwt.getClaim ("loginName") .asString ();} catch (JWTDecodeException e) {return null;}} / * get the login user ID * @ param token * @ return * / public static String getUserId (String token) {try {DecodedJWT jwt = JWT.decode (token) Return jwt.getClaim ("userId") .asString ();} catch (JWTDecodeException e) {return null }} / * generate signature, expire after 15min * * @ param username user name * @ return encrypted token * / public static String sign (String username,String userId) {try {/ / expiration time Date date = new Date (System.currentTimeMillis () + EXPIRE_TIME) / / Private key and encryption algorithm Algorithm algorithm = Algorithm.HMAC256 (TOKEN_SECRET); / / set header information Map header = new HashMap (2); header.put ("typ", "JWT"); header.put ("alg", "HS256") / / with username,userId information, generate the signature return JWT.create () .withHeader (header) .withClaim ("loginName", username) .withClaim ("userId", userId) .withExpiresAt (date) .sign (algorithm) } catch (UnsupportedEncodingException e) {return null;}

Create a TokenInterceptor interceptor

Package xyz.amewin.interceptor;import com.alibaba.fastjson.JSONObject;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import xyz.amewin.util.ApiResponse;import xyz.amewin.util.Contant;import xyz.amewin.util.JwtUtil;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;import java.util.HashMap;import java.util.Map / * * @ author Amewin * @ date 22:42 on 2020-4-17 * here interceptor * / public class TokenInterceptor implements HandlerInterceptor {/ * the difference between interceptor and filter * 1. The interceptor intercepts the access controller * and @ RequestMapping (value = {"/ test"}) * in a nutshell, it is the url * application of the access method: it can be used as the judgment of permissions, * 2. The filter is for global requests * including: css/js/html/jpg/png/git/... * and static files * 20200417 23:13 * / @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println ("perform this operation before executing the method!") ; response.setCharacterEncoding ("utf-8"); Cookie cookie=getCookieByName (request, "_ COOKIE_NAME"); / / if logged in, do not intercept if (null! = cookie) {/ / verify whether token is correct boolean result = JwtUtil.verify (cookie.getValue ()); if (! result) {return false } return true;} / / if you are not logged in, jump to the login interface else {/ / redirect the first call controller method response.sendRedirect (request.getContextPath () + "/ login") / / redirect the second redirection method / / request.getRequestDispatcher ("WEB-INF/jsp/login.jsp") .forward (request, response); / / System.out.println (request.getContextPath ()); return false / * the following is to return to the operation after a successful login without skipping to the main interface * implementation: by saving the request URL to the beforePath of session Then determine whether beforePath is empty at login * /}} @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler) Exception ex) throws Exception {} / * get cookie * * @ param request * @ param name cookie name * @ return * / public static Cookie getCookieByName (HttpServletRequest request, String name) {Map cookieMap = ReadCookieMap (request) If (cookieMap.containsKey (name)) {Cookie cookie = cookieMap.get (name); return cookie;} else {return null;}} / * encapsulate cookie into Map * * @ param request * @ return * / private static Map ReadCookieMap (HttpServletRequest request) {Map cookieMap = new HashMap () Cookie [] cookies = request.getCookies (); if (null! = cookies) {for (Cookie cookie: cookies) {cookieMap.put (cookie.getName (), cookie);}} return cookieMap } / * return information to client * * @ param response * @ param out * @ param apiResponse * / private void responseMessage (HttpServletRequest request, HttpServletResponse response, PrintWriter out, ApiResponse apiResponse) throws IOException {response.setContentType ("application/json; charset=utf-8"); out.print (JSONObject.toJSONString (apiResponse)); out.flush (); out.close ();}}

Spring-mvc.xml configuration interceptor:

Use in the controller

/ / query the database, log in to PwUser pwUser = loginService.jsonLogin (username, password); if (pwUser! = null) {json.setSuccess (true); json.setMsg ("login succeeded!") ; String token = JwtUtil.sign (pwUser.getUsernuber (), pwUser.getUserid (). ToString ()); if (token! = null) {Cookie cookie = new Cookie ("_ COOKIE_NAME", token); cookie.setMaxAge (3600); / / set token validity time cookie.setPath ("/") Response.addCookie (cookie);} else {json.setMsg ("wrong password or account!") ;}} else {json.setMsg ("wrong password or account!") ;}

The last point is to configure the load spring-mvc interceptor in web.xml

DispatcherServlet org.springframework.web.servlet.DispatcherServlet contextConfigLocation classpath:spring-mvc.xml 1 and above are all the contents of this article entitled "how to use token to achieve the function of verifying login in ssm". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report