Password encryption and microservice authentication JWT -- login function

Keywords: Lombok Apache axios

[TOC]

Preface

I wrote an article before:< Detailed instruction of JWT for password encryption and microservice authentication>

Practical operation (practice example)

pom(common), add jwt dependency on the original basis

  <dependencies>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.20</version>
        </dependency>
        <!--tool-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

        <!--jwt rely on-->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.7</version>
        </dependency>
    </dependencies>

Copy tool class

Ensure that there are Ras files in the local area (previously written about the production of RAS Click to go)

Project integration JWT

1. Generate token when logging in, and return

2. After the front-end login, save the token to sessionstream

3. In each request, the request header needs to be added

4. In gateway, write gateway filter to verify the request

1. Generate token when logging in, and return

UserController

private static final String priKeyPath = "D:\\ras\\ras.pri";


    @PostMapping("/login")
    public BaseResult login(@RequestBody TEmp tEmp) {
        TEmp result = empService.login(tEmp);
        if (result != null) {
            String token = null;
            try {
                token = JwtUtils.generateToken(result, 30, RasUtils.getPrivateKey(priKeyPath));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return BaseResult.ok("Login successful").append("token", token);
        } else {
            return BaseResult.error("User name or password mismatch");
        }
    }

2. After the front-end login, save the token to sessionstream

3. In each request, the request header (api.js) needs to be added

axios.interceptors.request.use(request => {
    //In each request header, the request header needs to carry a token
    //Get token
    let token = sessionStorage.getItem('token')
    //Release if set
    if (token) {
      request.headers.authorization = token
    }
    return request
  }, error => { });
  

4. In gateway, write gateway filter to verify the request

package com.czxy.filter;

import com.czxy.common.utils.JwtUtils;
import com.czxy.common.utils.RasUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.catalina.User;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Cloud before court
 * @Date 2019/12/23 8:31
 * @description
 */
@Component
public class LoginFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        //1 get tool class (request context object)
        RequestContext requestContext = RequestContext.getCurrentContext();
        //2. Obtain the request object through the tool class
        HttpServletRequest request = requestContext.getRequest();

        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        if ("/api/service/emp/login".equals(requestURI)) {
            return false;
        }
        return true;  //Whether to implement
    }

    private static final String pubKeyPath = "D:\\ras\\ras.pub";

    @Override
    public Object run() throws ZuulException {
        //1. Get tool class (request context)
        RequestContext requestContext = RequestContext.getCurrentContext();
        //2. Get request object
        HttpServletRequest request = requestContext.getRequest();
        //3. Get request header, get token value
        String token = request.getHeader("authorization");
        //4. Judgment verification
        try {
            JwtUtils.getObjectFromToken(token, RasUtils.getPublicKey(pubKeyPath), User.class);
        } catch (Exception e) {
            e.printStackTrace();
            //No release allowed
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(403);
        }
        //Release
        return null;
    }
}

5. The login interceptor (index.js) does not log in and jumps back to the login page. If it is logged in, it will be released

  /**Configuring Interceptors  */
  router.beforeEach((to,from,next)=>{
    if(to.path=='/login'){
    next()
    return
    }
    /**If there is a token indicating login, the program will jump, otherwise it will jump to the login page */
  let token=  sessionStorage.getItem('token')
    if(token){
      next()
    }else{
        next('/login')
    }
  })

Posted by jsinker on Mon, 23 Dec 2019 08:22:10 -0800