SpringBoot practice: integration with Vue element admin login

The previous blog has the login integration of Vue element admin: Login integration This time, a simplified version is written. Only the user/login, user/logout and user/info interfaces required by the front end are needed. Login realizes token generation. Logout directly exits login without operation logic. info takes the token after vuex exists after login returns the token, takes the permission of the current user, and reads out the returned roles list. The permissions correspond to different routing paths, The back-end demo is written freely on git. You can refer to: back-end

catalogue

Vue element admin environment   

npm dependency and its problems

api request modification

Back end environment

Cross domain and Solutions

Users and permissions

Return value encapsulation

Interface method

Vue element admin environment   

link The tutorial is very detailed, vue is quick to start, and the element UI is integrated, so you can use it when you use it;

npm dependency and its problems

① The version of node.js should not be too high. Version 8 is recommended;

② Specify Taobao image during npm install;

npm config set registry https://registry.npm.taobao.org
npm install --registry=https://registry.npm.taobao.org
npm run dev

③ sass relies on error reporting

// Change the version in package.json
"sass-loader": "^8.0.0",Replaced with "sass-loader": "^7.3.1",
npm uninstall sass-loader  //uninstall
npm install sass-loader@7.3.1 --save-dev   //Install the specified version

api request modification

vue uses the axios module for front-end request processing. In the login module, only the three interfaces mentioned above are required. In vue element admin master YZG \ SRC \ API \ user.js, they are post, get and post methods respectively. For the first login, the user returns token and info to get permission;

import request from '@/utils/request'

export function login(data) {
  return request({
    url: '/vue-element-admin/user/login',
    method: 'post',
    data
  })
}

export function getInfo(token) {
  return request({
    url: '/vue-element-admin/user/info',
    method: 'get',
    params: { token }
  })
}

export function logout() {
  return request({
    url: '/vue-element-admin/user/logout',
    method: 'post'
  })
}

Modify the default mock request to the local backend interface env.development:

# base api
#VUE_APP_BASE_API = '/dev-api'
VUE_APP_BASE_API = 'http://localhost:8080/'

Back end environment

The easiest way to pass through the back end is provided here;

Cross domain and Solutions

First, solve the cross domain problem. If the subsequent interfaces are not intercepted, the interceptor method always reports errors. Therefore, directly make a configuration class and set the cross domain request to a fixed request header;

package com.yzg.demo.utils;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
@WebFilter(filterName = "CORSFilter", urlPatterns = {"/*"})
@Order(value = 1)
@Configuration
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throws IOException, ServletException {
        System.out.println("Filter The filter was executed");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // The response header specifies the URI path that can access the resource
        response.setHeader("Access-Control-Allow-Origin", "*");
        //The response header specifies one or more methods allowed when the response accesses the resource
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        //Sets the maximum number of seconds the cache can survive
        response.setHeader("Access-Control-Max-Age", "3600");
        //Set supported request headers
        response.setHeader("Access-Control-Allow-Headers", "*");
        // Indicates whether the response to the request can be exposed to the page. When the true value is returned, it can be exposed
        response.setHeader("Access-Control-Allow-Credentials","true");
        filterChain.doFilter(servletRequest, servletResponse);
    }
    @Override
    public void destroy() {}
}

Users and permissions

Log in to login for user authentication for the first time. All subsequent requests must carry token s, or they can be retrieved by themselves after being intercepted by the back end. Therefore, the user has corresponding role permissions. Here, in order to pass the authentication, all ueser requests are returned to the admin user (fixed);

package com.yzg.demo.service;

import com.yzg.demo.model.user.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl {

    // Simulate Query Library Operation
    public List<User> initUserData(){
        User user4=new User("admin","admin","111111");

        List<User> userList=new ArrayList<User>();
        userList.add(user4);
        return userList;
    }

    public User findByUsername(User user){
        return initUserData().stream().filter(i->i.getUsername().equals(user.getUsername())).collect(Collectors.toList()).get(0);
    }
    public User findUserById(String userId) {

        return initUserData().stream().filter(i->i.getId().equals(userId)).collect(Collectors.toList()).get(0);
    }

}
package com.yzg.demo.service;
import com.yzg.demo.model.user.Role;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl {
    public Role getRoleFromToken(String token){

        List<String> roleList =new ArrayList<String>();
        roleList.add("admin");
        String introductions="I am a super administrator";
        String avatar="https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
        String name="Super Admin";
        return  new Role(name,roleList,introductions,avatar);
    }
}

Return value encapsulation

The receiving object of the front end is a json body, so annotation conversion is required when the method returns. In order to pass the verification, the return bodies of the three methods are sucess by default;

package com.yzg.demo.model.reponse;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties
public  class BaseResponse {
    @JsonProperty("code")
    int code;
    @JsonProperty("data")
    Object data;

    public BaseResponse(int code, Object objectData) {
        this.code = code;
        this.data = objectData;
    }

    public static  BaseResponse success(Object data){
        return new BaseResponse(20000,data);
    }
}

Interface method

Generally, database operations are required for user and permission queries. Here, we provide preset arrays. The interface returns to see what vue front-end wants and gives;

package com.yzg.demo.controller;

import com.yzg.demo.annotation.PassToken;
import com.yzg.demo.annotation.UserLoginToken;
import com.yzg.demo.model.reponse.BaseResponse;
import com.yzg.demo.model.user.User;
import com.yzg.demo.service.RoleServiceImpl;
import com.yzg.demo.service.TokenService;
import com.yzg.demo.service.UserServiceImpl;
import com.yzg.demo.utils.TokenUtils;
import io.swagger.annotations.ApiOperation;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/vue-element-admin/user")
public class UserController {
	@Autowired
	UserServiceImpl userService;
	@Autowired
	TokenService tokenService;

	@Autowired
	RoleServiceImpl roleService;
	// Sign in
	@ApiOperation(value = "Login interface", notes = "Login interface")
	@PostMapping("/login")
	@ResponseBody
	public BaseResponse login(HttpServletResponse response,
						@RequestBody User inputUser) throws JSONException {
		User userForBase = new User();
		inputUser.getUsername();
		userForBase.setId(userService.findByUsername(inputUser).getId());
		userForBase.setUsername(userService.findByUsername(inputUser).getUsername());
		userForBase.setPasswd(userService.findByUsername(inputUser).getPasswd());
		if (!userForBase.getPasswd().equals(inputUser.getPasswd())) {
			String info="Login failed,Password error";
			return BaseResponse.success(info);
		} else {
			String token = tokenService.getToken(userForBase);
			String info=token;
			Cookie cookie = new Cookie("token", token);
			cookie.setPath("/");
			response.addCookie(cookie);
			return BaseResponse.success(info);
		}
	}

	// verification
	@ApiOperation(value = "info", notes = "info")
	@GetMapping("/info")
	@ResponseBody
	public BaseResponse getInfo(){
		return BaseResponse.success(roleService.getRoleFromToken(""));
	}

	//logout
	@ApiOperation(value = "logout", notes = "logout")
	@PostMapping("/logout")
	@ResponseBody
	public BaseResponse logout(){
		return BaseResponse.success("sign out");
	}

	@ApiOperation(value = "pick up information", notes = "pick up information")
	@GetMapping("/checkNow")
	public String getMessage() {
		// Take out the user id in the token for operation
		System.out.println(TokenUtils.getTokenUserId());

		return "You have passed the verification";
	}

}

In this way, login integration is realized;

Keywords: Java Spring Boot Vue.js

Added by tnylsej on Fri, 17 Sep 2021 23:45:35 +0300