Home  >  Article  >  Java  >  How does Java implement user login token?

How does Java implement user login token?

PHPz
PHPzforward
2023-04-21 22:43:062420browse

1. Flow chart

How does Java implement user login token?

2. Token

1. Token is a client authentication mechanism and is an encrypted string. Strong security, supports cross-domain

2. When a user logs in for the first time, the server verifies that the UserId and Password are legal through the database, and then generates a token string based on the random number userid and the current timestamp through DES encryption

  • Of course the specific way to generate tokens is defined by the developer

3. Token generation generally uses uuid to ensure uniqueness. When the user logs in When generating a unique token, the storage is generally stored in the database

  • The token expiration time is to store the token twice in the cookie or session, and maintain it according to the expiration time of the cookie and session. Token expiration time

#4. Token is generated on the server side. If the front end uses the username/password to request authentication from the server, and the server authentication is successful, the server will return a Token to the front end. The front end can bring Token with each request to prove its legal status

5. Token is a token. Its biggest feature is randomness and unpredictability. Generally hackers or software cannot guess it

3. Analysis

Create a token token and give the user a unique token value when logging in. Assign this token value when logging in. Brand

Create a Util folder in the SpringBoot project

Create the TokenUtil.java file under the folder

public class TokenUtil {  
    private static Map<String, User> tokenMap = new HashMap<>();  
    public static String generateToken(User user){
        //生成唯一不重复的字符串
        String token = UUID.randomUUID().toString();
        tokenMap.put(token,user);
        return token;
    }
 
    /**
     * 验证token是否合法
     * @param token
     * @return
     */
    public static  boolean verify(String token){
        return tokenMap.containsKey(token);
    }
 
    public static User gentUser(String token){
        return tokenMap.get(token);
    }
 
    public static void main(String[] args) {
        for (int i = 0; i < 20; i++){
            System.out.println(UUID.randomUUID().toString());
        }
    } 
}

User login UserController .java

@Api( tags = {"用户模块接口"})
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
 
    @Autowired
    private HttpSession session;
    @ApiOperation("登录接口")
    @RequestMapping(value = "login",method ={RequestMethod.POST,RequestMethod.GET})
    public Map<String,Object> login(User user){
        Map<String,Object> map = new HashMap<>();
        map.put("code",0);
        if(StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword()) ){
            map.put("msg","用户或者密码为空!");
            return map;
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername())
                .eq("password",user.getPassword());
        User userDb = userService.getOne(queryWrapper);
        if(userDb != null){
            String token= TokenUtil.generateToken(userDb);
            map.put("code",1);
            map.put("data",userDb);
            map.put("token",token);
            session.setAttribute("username",userDb.getUsername());
        }else{
            map.put("msg","用户名或密码错误!");
        }
        return map;
    }
    @ApiImplicitParams(
            {
            @ApiImplicitParam(name = "id",
                    value = "用户id", required = true,
                    dataType = "Long"),
            @ApiImplicitParam(name = "name",
                    value = "测试名字",
                    dataType = "string")
            }
    )
    @ApiOperation("根据id查询用户信息")
    @RequestMapping(value="getById",method ={RequestMethod.POST,RequestMethod.GET})
    public  User getById(Long id ,String name){
        System.out.println(name);
        return userService.getById(id);
    }
 
}

Operate the interceptor on the interceptor. LoginInterceptor.java

public class LoginInterceptor implements HandlerInterceptor {
 
    @Autowired
    private HttpSession httpSession;
 
    //Controller逻辑执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle....");
        String uri = request.getRequestURI();
        System.out.println("当前路径:"+uri);
        /**
         * HandlerMethod=>Controller中标注@RequestMapping的方法
         *  需要配置静态资源不拦截时,添加这块逻辑  => 前后端分离项目
         *
         */
        // 是我们的conrtoller中的方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("qcby-token");
        if (!TokenUtil.verify(token)) {
            // 未登录跳转到登录界面
           throw  new RuntimeException("no login!");
        } else {
            return true;
        }
    }
 
    //Controller逻辑执行完毕但是视图解析器还未进行解析之前
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle....");
    }
 
    //Controller逻辑和视图解析器执行完毕
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion....");
    }
}

4. Running results

http://localhost:8080/

How does Java implement user login token?

http://localhost:8080/user/login?username=admin&password=123456

How does Java implement user login token?

## Remember this token

60227b0e-bdbb-47d9-9df4-f56163cb529d

In postman

How does Java implement user login token?

Write the token and the output is successful

How does Java implement user login token?

The above is the detailed content of How does Java implement user login token?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete