SoFunction
Updated on 2025-03-03

Spring boot+VUE token verification sample code

1. Steps

Vue+Spring Boot can be divided into six steps to implement token authentication:

1. Log in to the front end, post username and password to the back end.

2. The backend verifies the user name and password. If it is passed, generate a token and return it to the frontend.

3. Get the token in the front end and use vuex and localStorage to manage it, and log in and enter the homepage successfully.

4. After that, every permission operation in the front-end needs to determine whether a token exists, if it does not exist, jump to the login page.

5. Every request to the backend after the front end must have a token on the request header. The backend checks whether there is a token in the request header, and checks whether it expires after the token, and returns the corresponding status to the front end. (Usually, it returns 401 if it fails)

6. If the token has expired, clear the token information and jump to the login page.

2. Backend

1. Lead dependency

<!--        To be used-->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.0</version>
        </dependency>

2. Add token tool class

.withClaim(“Username”, ())
My project does not have a user password, so I only use one Username here. If there is a password, you can add one more line, for example:

.withClaim(“Password”, ())

package ;
import com.;
import com.;
import com.;
import com.;
import ;

import ;


public class TokenUtil {
    private static final long EXPIRE_TIME= 10*60*60*1000;   //Ten hours    private static final String TOKEN_SECRET="123456";  //Key Salt    /**
      * Signature generation
      * @param staff
      * @return
      */
    public static String sign(staff staff){
        String token = null;
        try {
            Date expiresAt = new Date(() + EXPIRE_TIME);
            token = ()
                    .withIssuer("auth0")
                    .withClaim("Username", ())
//                    .withAudience(())
                    .withExpiresAt(expiresAt)
                    // The HMAC256 encryption algorithm is used.                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (Exception e){
            ();
        }
        return token;
    }
    /**
      * Signature verification
      * @param token
      * @return
      */
    public static boolean verify(String token){
        try {
            JWTVerifier verifier = (Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
            DecodedJWT jwt = (token);
            ("Certification passed:");
            ("Username: " + ("Username").asString());
            ("Expiration date: " + ());
            return true;
        } catch (Exception e){
            return false;
        }
    }
}

3. Add an interceptor

The main function of this interceptor is to intercept some requests without tokens and return error messages. If there is token, you can pass directly

package ;
import ;
import ;
import ;
import ;
import ;
import ;


@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler)throws Exception{
        if(().equals("OPTIONS")){
            (HttpServletResponse.SC_OK);
            return true;
        }
        ("utf-8");
        String token = ("token"); //The front-end vue adds token in the request header//        (());
        if(token != null){
            boolean result = (token);
            if(result){
                ("Through Interceptor");
                return true;
            }
        }
        ("UTF-8");
        ("application/json; charset=utf-8");
        try{
            JSONObject json = new JSONObject();
            ("msg","token verify fail");
            ("code","50000");
            ().append(());
            ("Authentication failed, interceptor failed");

        }catch (Exception e){
            ();
            (500);
            return false;
        }
        return false;
    }
}

4. Configure cross-domain and process requests

Note: The interface intercepted here is the backend, not the frontend.

In the ' /** 'Whether it is restful or there is a long list of addresses behind it can be recognized

(“/toLogin/**”);

package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    /**
      * Turn on cross-domain
      */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // Setting allowed routing across domains        ("/**")
                // Set the domain name that allows cross-domain requests                .allowedOriginPatterns("*")
// Set the allowed method                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
                // Whether to allow cookie parameters                .allowCredentials(true)
                // Set the allowed method                .allowedMethods("*")
                // Cross-domain time allowed                .maxAge(4600);
    }


    private TokenInterceptor tokenInterceptor;
    //Construction method    public WebMvcConfig(TokenInterceptor tokenInterceptor){
         = tokenInterceptor;
    }

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer){
        (new ConcurrentTaskExecutor((3)));
        (30000);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        List<String> excludePath = new ArrayList<>();
        //Exclude interception, except for registering and logging in (there is no token at this time), all others are intercepted//        ("");  //Log in        ("/toLogin/**");  //Log in// ("/admin/login"); //Register//        ("/**");
        ("/img/**");  // Static resources        ("/song/**");  // Static resources
        (tokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(excludePath);
        (registry);
    }

}

5. Login interface

@GetMapping("/toLogin/{username}")
    public Object toLogin(@PathVariable("username") String username){
        staff staff = (username);
        JSONObject jsonObject = new JSONObject();
        if(staff!=null){
            String token = (staff);
            ("token",token);
            ("staff",staff);
            ("msg","Login successfully");
            ("code",200);
        }else {
            ("msg","Error account or password");
            ("code",500);
        }
        return jsonObject;
    }

3. Front end

Configuration

Add route front guard beforeEach to intercept requests, 2. Add request interceptor in axios:

//Global pre-guard((to,from,next) => {
  // if( === '/register' || === '/login' || === '/'){ //If you enter the login and registration page ==> pass    if( === '/register' ||  === '' ||  === '/'){
    next()
  }else{ 
    let userToken = ('token');
    // ("Token is:"+userToken);    if(userToken == null || userToken == ''){
      alert("No permission, please log in first!");
      return next('/');
    }else{
      next();
    }
  }
}),


//Request interceptor Add token in the request header(
    config => { // Set the obtained token to the token in the header        if(('token')){
             = ('token');
        }
        return config;
    },
    error => {
        return (error);
    }
)

2. Configure Vuex

Remember to download Vuex's dependencies before configuring

cnpm install vuex --save

How to use vuex (can not read)

store/

import Vue from 'vue'
import Vuex from 'vuex'
 
 (Vuex)
 
export default new ({
  state: {
      user: ('staff') ? ('staff') : null,
      //If localSorage exists token, assign the value to      token: ('token') ? ('token') : null
  },
  mutations: {
      setUsername(state, staff) {
           = staff
          // (ary)
          //Save staff in JSON format          ('staff', (staff))
          
      },
      setToken(state, token) {
          ('token', token)
           = token
      },
       //I wrote a logout button on the page so I added a logout to clear the data in localStorage      logout(state) {
          ('token')
           = null
          ('staff')
           = null
           //The RSA encryption I wrote requires the public key to obtain from the backend. In order to facilitate me to directly store it in localStorage after getting the public key, so I need to clear it here.          ('publickey')
          =null
          
      }
  }
})

3. Login method

Remember to guide the package

import store from ‘…/store/’

import store from '../store/'
    export default {
       data() {
         return {
           ruleForm: {     pass: '',    username: ''},
           staff:null,
        }
    },
       methods: {
}
submitForm() {
            var vm=this;
            ('http://localhost:8090/toLogin/'++''
            ).then(function (response) {
                ()
                if( == 200){//Save token and user in localStorage                       ('setToken',)
                       ('setUsername',)
                       //Skip to the page after login is successful                       ("========"+)
                       vm.$('/index')
                       //Get the staff in local storage                       =(('staff'))
                       ();
                       }
                       else{
                         alert()
                            }    
            }).catch(function (e) {
                (e)
                })
         }

4. Log out

Log out, remember to import the package

import store from ‘…/store/’

 loginOut(){
          ('logout')  
      }

Why don't Spring boot+VUE do not need session?
Because the session exists with the server, the cross-domain session will change.

This is the end of this article about the example code for Spring boot+VUE token verification. For more relevant Spring boot VUE token verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!