Personal learning series-Spring Boot integrates JWT to achieve certification

Posted May 27, 20204 min read

How to ensure the user is logged in? Re-login overtime? JWT is here.

What is JWT

JWT(Json Web Token) is a tool in the form of a string of XXXX.XXXX.XXXX. JWT transfers insensitive information stored in JWT between users and servers in a secure manner.

Why use JWT

Imagine a scenario where after we log in to a website, we close the webpage or browser. The next time we open the webpage, it may still display the status of login. No need to log in again, such a user authentication can be achieved through JWT Function. Of course, using Session can achieve this function, but using Session will also increase the storage pressure of the server, and JWT distributes the storage pressure to each client machine to reduce the pressure on the server.

JWT operation flowchart

Picture.png

Spring Boot integration

1 . Pom.xml configuration dependency

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

2 . Add filter

This class declares a JWT filter class, extracts the JWT information from the Http request, and uses the secretkey ** key to verify the JWT.

/**
* Interceptor verification class
* @author zhouzhaodong
* /
public class JwtFilter extends GenericFilterBean {

   /**
     * Secret key
     * /
    public static final String SECRET_KEY = "secretkey";

    @Override
    public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
            throws IOException, ServletException {

        final HttpServletRequest request =(HttpServletRequest) req;
        final HttpServletResponse response =(HttpServletResponse) res;

        //Get authorization from request
        final String authHeader = request.getHeader("authorization");

        //If the Http request is OPTIONS, then just return status code 200.
        String options = "OPTIONS";
        if(options.equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        }
        else {

            //Determine whether the token starts with Bearer
            String header = "Bearer";
            if(authHeader == null ||! authHeader.startsWith(header)) {
                throw new ServletException("Missing or invalid Authorization header");
            }

            //Then get the JWT token from the authorization
            final String token = authHeader.substring(7);

            try {
                //Use the JWT parser to check whether the signature is valid with Key "secretkey".
                final Claims claims = Jwts.parser(). setSigningKey(SECRET_KEY) .parseClaimsJws(token) .getBody();

                //Add claims to the request header
                request.setAttribute("claims", claims);
            } catch(final SignatureException e) {
                throw new ServletException("Invalid token");
            }

        }
        chain.doFilter(req, res);
    }
}

3 . Interceptor

/**
* Interceptor
* @author zhouzhaodong
* /
@Configuration
public class JwtCfg {

    @Bean
    public FilterRegistrationBean <JwtFilter> jwtFilter() {
        final FilterRegistrationBean <JwtFilter> registrationBean = new FilterRegistrationBean <>();
        registrationBean.setFilter(new JwtFilter());
        //Intercept and verify the URL under/test/*
        registrationBean.addUrlPatterns("/test/*");

        return registrationBean;
    }
}

4 . Write a method class generated by JWT

/**
* JWT generated class
* @author zhouzhaodong
* /
public class JwtUtils {

    public static final String SUBJECT = "admin";

   /**
     * Expiry time, milliseconds, one day
     * /
    public static final long EXPIRE = 1000 * 60 * 60 * 24;

   /**
     * Secret key
     * /
    public static final String SECRET_KEY = "secretkey";

   /**
     * Generate jwt
     * @param userName
     * @param passWord
     * @return
     * /
    public static String geneJsonWebToken(String userName, String passWord) {

        if(StringUtils.isEmpty(userName) || StringUtils.isEmpty(passWord)) {
            return "Username or password cannot be empty";
        }

        return Jwts.builder(). setSubject(SUBJECT)
                .claim("userName", userName)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY) .compact();
    }

}

5 . Write test method

/**
* Login
* @author zhouzhaodong
* /
@RestController
public class TestController {

    @RequestMapping("/login")
    public String login(HttpServletResponse response, String userName, String passWord) {
        //Pretend to judge whether the login is successful
        if(userName == null || "" .equals(userName) || passWord == null || "" .equals(passWord)) {
            return "Username or password cannot be empty";
        }
        String token = JwtUtils.geneJsonWebToken(userName, passWord);
        //Put the token in the response header
        response.setHeader("Authorization", token);
        return token;
    }

    @RequestMapping("/secure/check")
    public String check() {
        return "Login successful";
    }

}

6 . Start verification

1 . Run IDEA

Picture.png

2 . Use postman for testing

First you need to visit login to get the token:
Picture.png

Then take the token to log in:
Picture.png

Completed, is it relatively simple!

Source address

https://github.com/zhouzhaodo...

http://www.zhouzhaodong.xyz