Implementation of SpringCould+Vue3-Element-Admin login interface, user information interface and Token verification【Taurus Education Platform】

1. Implementation of SpringCould+Vue3-Element-Admin login interface, user information interface and Token verification【Taurus Education Platform】

1.1 Background

This project is reconstruction: Xingzhi online comprehensive education platform. This project was renamed: Taurus Education Platform

Keywords: SpringBoot, SpringCould, Vue3, Uni-app

The front-end background management system adopts an open source project: Vue3-Element-Admin.

This article is mainly to realize the login interface of SpringCould+Vue3-Element-Admin background management system, user information interface and Token verification implementation

1.2 Database

image-20230417160848283

2. Login interface and its Token implementation

2.1 Front end

The front end uses an open source project: Vue3-Element-Admin

The following are all magic changes to the code of Vue3-Element-Admin.

The login page is as follows:

image-20230417165812848

Analyze the request interface return value of the original project:

image-20230417170045064

Request payload:

image-20230417170114619

Change the front-end request interface:

Interface directory location: Src->api->login.js

// 登录接口
export const Login = data => {
    
    
  return request({
    
    
    url: 'http://localhost:8001/user/login',
    // url: '/api/login',
    method: 'post',
    data,
  })
}

2.2 Backend

2.2.1 Control layer

The backend receives the value passed from the frontend:

Background login:

@PostMapping("/user/login")
@ResponseBody  //返回给前端一个文本格式
public Message login(@RequestBody BackLoginUser user) {
    
    
    Message msg=new Message();
    System.out.println(user.getUsername());
    System.out.println(user.getPassword());
    try {
    
    
        if (StringUtils.isEmpty(user.getUsername())) {
    
    
            msg.setMessage("登录失败,用户名不能为空");
            msg.setStatus(400);
            return msg;
        }
        if (StringUtils.isEmpty(user.getPassword())) {
    
    
            msg.setMessage("登录失败,密码不能为空");
            msg.setStatus(400);
            return msg;
        }
        msg = sysUserService.doLogin(user);
        return msg;

    } catch (Exception ex) {
    
    
        ex.printStackTrace();
    }
    return null;
}

Code explanation:

@RequestBody BackLoginUser user: The json string from the front end is stored in the user.

User has username and password respectively.

if (StringUtils.isEmpty(user.getUsername())) and if (StringUtils.isEmpty(user.getPassword())) are to exclude the case that the two fields of the login value are empty.

If normal, then continue down.

If there is no problem, it will be passed to the service layer to continue the logical operation (query whether the user exists, whether the account password is correct)

@Autowired
SysUserService sysUserService;

as follows:

msg = sysUserService.doLogin(user);
return msg;

2.2.2 service layer

code show as below:

    public Message doLogin(BackLoginUser user) {
    
    
        User userx = new User();
        Message msg=new Message();
        userx = sysUserDao.LoginByname(user.getUsername());
        System.out.println(userx);
        if (userx==null){
    
    
            msg.setMessage("用户不存在,请注册!");
            msg.setStatus(405);
            return msg;
        }else {
    
    
            if (user.getUsername().equals(userx.getUsername())
                    && user.getPassword().equals(userx.getPassword()) ){
    
    
                String token = CreateJwt.getoken(userx);
                Map<String, String> map = new HashMap<>();
                map.put("token",token);
                msg.setData(map);
                msg.setMessage("登录成功");
                msg.setStatus(200);
                return msg;
            }else {
    
    
                msg.setMessage("登录失败,密码错误");
                msg.setStatus(405);
                return msg;
            }
        }
    }

Code explanation:

The first two lines have nothing to say.

userx = sysUserDao.LoginByname(user.getUsername()); The Dao layer is called to perform data query operations.

The first if is to rule out the problem that the user does not exist (the user account is entered incorrectly).

Else is divided into successful login or wrong password.

A successful login means that a Token needs to be generated.

String token = CreateJwt.getoken(userx);

2.2.3 Tool class: CreateJwt

The getoken method is: generate Token, according to time, user id, user username, current time, and expiration time. The process is as follows.

    private static final String key = "0123456789_0123456789_0123456789";

    public static String  getoken(User user) {
    
    
        // 设置过期时间,这里设置为1小时
        long expirationTime = System.currentTimeMillis() + 3600000;
        SecretKey secretKey = new SecretKeySpec(key.getBytes(), SignatureAlgorithm.HS256.getJcaName());
        String jwt = Jwts.builder()
                .setId(user.getId()+"")
                .setSubject(user.getUsername())
                .setIssuedAt(new Date())
                .setExpiration(new Date(expirationTime)) // 设置过期时间
                .signWith(secretKey)
                .compact();
        return jwt;
    }

2.2.4 Dao-Mapper

Dao:

public User LoginByname(String username);

Mapper:

<select id="LoginByname" parameterType="String" resultType="User">
    select * from user where username = #{username};
</select>

3. Implementation of User Information Interface and Verification Token Function

3.1 Front end

Obtain login user information: Token is required to initiate a request. Sent to the backend, the backend needs to verify the Token before returning the value.

import axios from 'axios'

export const GetUserinfo = () => {
    
    
  const token = localStorage.getItem('VEA-TOKEN');

  return axios({
    
    
    method: 'get',
    url: 'http://localhost:8001/api/userinfo',
    headers: {
    
    
      'Authorization': 'Bearer ' + token,
    }
  });
};

After sending, we analyze the returned value.

image-20230417183532577

Change the data for obtaining user information: data.data

reason:

After connecting to the backend interface, I can't realize the user's information display. After troubleshooting, I found that if I want to get the value in data, I need data.data.

// 获取用户信息
    async getUserinfo() {
    
    
      const {
    
     status, data } = await GetUserinfo()
      if (+status === 200) {
    
    
        this.userinfo = data.data
        console.log("myurl:",data.data);
        return Promise.resolve(data)
      }
    },

Realize the effect:

image-20230417183920392

3.2 Backend

3.2.1 Control layer

User Info

 @GetMapping("/api/userinfo")
    public Message getUserInfo(@RequestHeader("Authorization") String token,
                               @RequestHeader("User-Agent") String userAgent) {
    
    
        Message msg=new Message();
        try{
    
    
            String[] parts = token.split("\\s+");
            String jwtToken = parts[1];
            System.out.println(jwtToken);
            String tokenValue = JsonPath.parse(jwtToken).read("$.token");
            System.out.println(tokenValue);
            msg = sysUserService.userinfo(tokenValue);

            return msg;
        } catch (Exception e) {
    
    
            return null;
        }

code explanation

@RequestHeader("Authorization") String token,: Accept the front-end pass value Token.

The value in try is my code for taking the Token value in the string.

sysUserService.userinfo is to pass the Token into the service for processing.

msg = sysUserService.userinfo(tokenValue);

3.2.3 service layer

code show as below:

public Message userinfo(String token) {
    
    
        Message msg=new Message();
        Claims claims = CreateJwt.parseToken(token);
        User userx = new User();
        System.out.println("claims.getId():"+claims.getId());
        userx = sysUserDao.LoginById(claims.getId());
        System.out.println(userx);
        Map<String, String> map = new HashMap<>();
        map.put("id", String.valueOf(userx.getId()));
        map.put("name",userx.getName());
//        role: 0 admin  1 teacher  0 student
        String role = "";
        if (userx.getRole()==0){
    
    
            role="admin";
        }if (userx.getRole()==1){
    
    
            role="teacher";
        }else {
    
    
            role="student";
        }
        map.put("role",role);
        map.put("avatar","https://s1.ax1x.com/2023/04/17/p9CjIr6.png");
        msg.setData(map);
        msg.setMessage("登录成功");
        msg.setStatus(200);
        return msg;
    }

userinfo mainly realizes token parsing and return value.

After writing this, I found that this piece has not been finished yet. I should judge the result of token analysis, and return status code 500 if it is wrong.

role is a simple judgment assignment: role: 0 admin 1 teacher 0 student

Use a HashMap to directly push the required data values, and finally put them in Data and pass them to the backend.

3.2.3 Tool class: CreateJwt

public static Claims parseToken(String token) {
    
    
    System.out.println(token);
    try {
    
    
        SecretKey secretKey = new SecretKeySpec(key.getBytes(), SignatureAlgorithm.HS256.getJcaName());
        Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();
        return claims;
    } catch (ExpiredJwtException e) {
    
    
        // Token已过期
        System.out.println("Token已过期");
    } catch (JwtException e) {
    
    
        // Token解析失败
        System.out.println("Token解析失败");
    }
    return null;
}

This piece of code is generated by me with Chatgpt, of course there is a small part of my debugging. Chatgpt is pretty well written.

This block is mainly for parsing tokens.

3.2.4 Dao-Mapper

Dao:

User LoginById(String id);

Mapper:

    <select id="LoginById"  parameterType="String" resultType="User">
        select * from user where id = #{id};
    </select>

Guess you like

Origin blog.csdn.net/weixin_52908342/article/details/130387431
Recommended