Bean Treasure community project actual combat tutorial introduction

This project is equipped with a free video tutorial, the supporting code is completely open source. Build from scratch the most widely used Springboot+Vue front-end and back-end separation multi-user community project. This project is of moderate difficulty. For your convenience, each video tutorial will correspond to each submission on Github.

Screenshot of project Home Page

Open source code address

The front end

Video Tutorial Address

Video tutorial

Front-end technology stack

Vue Vuex Vue Router Axios Bulma Buefy Element Vditor DarkReader

Back-end technology stack

Spring Boot Mysql Mybatis MyBatis-Plus Spring Security JWT Lombok

Get user information front end

1. In the viwes/login. Vue

this.$store.dispatch("user/getInfo")
Copy the code

2. API configuration

In the SRC/API/auth/auth. Js

// Get user information
export function getUserInfo() {
  return request({
    url: '/auth/user/info'.method: 'get'})}Copy the code

3.src\store\modules\user.js

It’s added. Just take a look

4.src\utils\request.js

Import, not import error information (Store is not defined)

import store from '@/store'
import { getToken } from '@/utils/auth'
Copy the code

Adding interceptors

// 2. Request interceptor
service.interceptors.request.use(
  config= > {
    // Do some processing before sending a request, such as data conversion, request header configuration, token setting, loading setting, etc
    // Note that the cookie method or the local localStorage method should be introduced when using the token. Js-cookie is recommended
    if (store.getters.token) {
      // config.params = {'token': token} // If required to carry in the parameters
      // config.headers.token = token; // If the request is carried in the request header
      // bearer: W3C specification
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error= > {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)
Copy the code

5. Page effects

After logging in, go back and request info.

The interceptor token

Add request path to isProtectedUrl method, only after login (have token to access, otherwise cannot access)

1. JwtAuthenticationFilter filter

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final PathMatcher pathMatcher = new AntPathMatcher();

    /** * intercepting method **@param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {
            if (isProtectedUrl(request)) {
// System.out.println(request.getMethod());
                if(! request.getMethod().equals("OPTIONS")) {
                    // Parse the token, if it is generated by us, then it can be parsedrequest = JwtUtil.validateTokenAndAddUserIdToHeader(request); }}}catch (Exception e) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            return;
        }
        filterChain.doFilter(request, response);
    }

    /** * protected requests (we'll replace these addresses later) **@param request
     * @return* /
    private boolean isProtectedUrl(HttpServletRequest request) {
        List<String> protectedPaths = new ArrayList<String>();
        protectedPaths.add("/auth/user/info");
        protectedPaths.add("/auth/user/update");
        protectedPaths.add("/post/create");
        protectedPaths.add("/post/update");
        protectedPaths.add("/post/delete/*");
        protectedPaths.add("/comment/add_comment");
        protectedPaths.add("/relationship/subscribe/*");
        protectedPaths.add("/relationship/unsubscribe/*");
        protectedPaths.add("/relationship/validate/*");

        boolean bFind = false;
        for (String passedPath : protectedPaths) {
            bFind = pathMatcher.match(passedPath, request.getServletPath());
            if (bFind) {
                break; }}return bFind;
    }

    @Bean
    public FilterRegistrationBean jwtFilter(a){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        JwtAuthenticationFilter filter = new JwtAuthenticationFilter();
        registrationBean.setFilter(filter);
        returnregistrationBean; }}Copy the code

Modifying boot Classes

Get user information back end

@requestheader (value = “userName”

www.bilibili.com/video/BV1Wz…

1.UmsUserController

@GetMapping("/info")
public ApiResult loginUserInfo(@RequestHeader(value = "userName") String userName) {
    UmsUser umsUser = umsUserService.getOne(
            new LambdaQueryWrapper<UmsUser>().eq(UmsUser::getUsername,userName)
    );
    return ApiResult.success(umsUser);
}
Copy the code

2. Test the page