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 implement token login with SpringBoot

2025-05-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly shows you "SpringBoot how to achieve token login", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "SpringBoot how to achieve token login" this article.

Why introduce token mechanism?

When performing login verification, we need a session or cookie session for verification. The clients include browsers, app, WeChat Mini Programs and official accounts. Only browsers have session and cookie mechanisms. When we leave the browser and use app to send requests to the server, there is no session and cookie mechanism. Then we need to use tokens for login verification.

Code implementation

First build a util package and create a TokenUtil class to generate token

TokenUtil class code

Package com.qcby.util; import com.qcby.entity.User; import java.util.HashMap;import java.util.Map;import java.util.UUID; public class TokenUtil {/ * create map to store all tokens * * token-User * / private static Map tokenMap=new HashMap () / * generate token, store token-user correspondence * return token token * @ param user * @ return * / public static String generateToken (User user) {/ / generate the unique string String token = UUID.randomUUID () .toString (); tokenMap.put (token,user); return token } / * verify whether token is legal * @ param token * @ return * / public static boolean verify (String token) {return tokenMap.containsKey (token);} / * * obtain user information according to token * @ param token * @ return * / public static User getUser (String token) {return tokenMap.get (token);}}

LoginInterceptor class code

Package com.qcby.interceptor; import com.qcby.util.TokenUtil;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession Public class LoginInterceptor implements HandlerInterceptor {/ / Controller logic execution before @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println ("preHandle...."); String uri = request.getRequestURI (); System.out.println ("current path" + uri) The method to mark @ RequestMapping in / * * HandlerMethod= > Controller * when static resources are not intercepted, add this logic = > the front and rear separation project * / if (! (handler instanceof HandlerMethod)) {return true;} String token=request.getHeader ("qcby-token") If (! TokenUtil.verify (token)) {/ / not logged in jumps to login interface throw new RuntimeException ("no login!");} else {return true }} / / Controller logic has been executed but before the view parser has parsed @ Override public void postHandle (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {System.out.println ("postHandle....") } / / Controller logic and view parser completed @ Override public void afterCompletion (HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {System.out.println ("afterCompletion....");}}

Implementation class

@ RestController@RequestMapping ("user") public class UserController {@ Autowired private UserService userService; @ ApiOperation ("user login interface") @ RequestMapping (value= "login", method = {RequestMethod.GET,RequestMethod.POST}) public Maplogin (User user) {Map map=new HashMap (); map.put ("code", 0) If (StringUtils.isEmpty (user.getUsername ()) | | StringUtils.isEmpty (user.getPassword () {map.put ("msg", "user or password is empty!") ; return map;} QueryWrapper queryWrapper=new QueryWrapper (); queryWrapper.eq ("username", user.getUsername ()) .eq ("password", user.getPassword ()); User user1=userService.getOne (queryWrapper); if (user1 invalid null) {String token= TokenUtil.generateToken (user1); map.put ("cod", 1) Map.put ("data", user1); map.put ("token", token);} else {map.put ("msg", "wrong username or password!");} return map;}}

The interceptor class can refer to this article, and this token validation is changed on the interceptor.

SpringBoot interceptor implements login interception

Postman authentication is required

The above is all the contents of the article "how to achieve token login in SpringBoot". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more 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