Personal learning series – spring boot integrates JWT to realize authentication

Time:2020-9-17

How to ensure the real login of users? Re login after timeout? JWT is here.

What is JWT

JWT (JSON web token) is a tool with the format of XXXX.XXXX.XXXX JWT transfers insensitive information stored in JWT between user and server in a secure way.

Why use JWT

Imagine such a scenario, after we log in to a website, and then close the web page or browser. The next time we open a web page, the login status may be displayed. It is not necessary to log in again. Such a user authentication function can be realized through JWT. Of course, using session can achieve this function, but using session will also increase the storage pressure of the server. JWT distributes the storage pressure to each client machine, so as to reduce the pressure on the server.

JWT operation flow chart

Personal learning series - spring boot integrates JWT to realize authentication

Spring boot integration

One 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 that extracts JWT information from HTTP requests and uses thesecretkeyThis key validates JWT.

/**
 *Interceptor validation 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, you only need to return the status code 200.
        String options = "OPTIONS";
        if (options.equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        }
        else {

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

            //The JWT token is then obtained from the authorization
            final String token = authHeader.substring(7);

            try {
                //Use the JWT parser to check whether the signature is valid with the key "secret key".
                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 generation class
 * @author zhouzhaodong
 */
public class JwtUtils {

    public static final String SUBJECT = "admin";

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

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

    /**
     *Generating JWT
     * @param userName
     * @param passWord
     * @return
     */
    public static String geneJsonWebToken(String userName, String passWord) {

        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(passWord)) {
            Return "user name 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. Writing test method

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

    @RequestMapping("/login")
    public String login(HttpServletResponse response, String userName, String passWord) {
        //Pretend to judge if the landing is successful
        if(userName == null || "".equals(userName) || passWord == null || "".equals(passWord)){
            Return "user name 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 "successfully logged in";
    }

}

6. Start verification

1. Run idea

Personal learning series - spring boot integrates JWT to realize authentication

2. Test with postman

First, you need to access login to get the token:
Personal learning series - spring boot integrates JWT to realize authentication

Then take the token to log in:
Personal learning series - spring boot integrates JWT to realize authentication

It’s finished, isn’t it easy!

Source code address

https://github.com/zhouzhaodo…

Personal website links

http://www.zhouzhaodong.xyz

Recommended Today

How to share queues with hypertools 2.5

Share queue with swote To realize asynchronous IO between processes, the general idea is to use redis queue. Based on the development of swote, the queue can also be realized through high-performance shared memory table. Copy the code from the HTTP tutorial on swoole’s official website, and configure four worker processes to simulate multiple producers […]