Token-based SSM login authentication

1. What is the token

token means "token" is a series of strings, the server generates, as a client identification requests.

When the user first logs in, the server generates a token and this token is returned to the client after the client request came just take this token data without the need to bring the user name and password again.

Simple token of the composition; uid (user's unique identity), time (timestamp of the current time), sign (Signature, the first few token hexadecimal string of hashing algorithm to compress into a certain length is. prevent leakage token)

2, SSM XML-based configuration

pom.xml introduced

        <!-- token -->
       <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>2.2.0</version>
       </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>

spring-mvc.xml

Configuring interceptors

< Mvc: interceptors > 
        <-! Using a bean definition Interceptor, directly defined in mvc: interceptors below the root Interceptor will intercept all requests -> 
        ! <- <bean class = "com.bybo.aca.web. interceptor.Login "/> -> 
        < MVC: interceptor > 
            <-! intercept: / ** denotes intercept all the Controller -> 
            < MVC: Mapping path =" / ** "  /> 
            <-! not intercept -> 
            < MVC: Mapping the exclude- path = "/ the User / the Login" /> 
             <-! not intercept -> 
            < MVC: Mapping the exclude- path = "/ GET / tableInforAllByStatus" />
            <bean class="com.baccarat.util.JWTInterceptor" />
        </mvc:interceptor>
    </mvc:interceptors>

Interceptor entity classes

Package Comkbchcrtkutil;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.baccarat.controller.UserController;
import com.baccarat.entity.User;


@Component
public class JWTInterceptor implements HandlerInterceptor{
    public static Logger logger = Logger.getLogger(UserController.class);

    
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
 
    }
 
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub
 
    }
 
    /**
     * Token validates the interceptor
     * @author Stephen
     * @time 2019-10-11 17:00:32
     * */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws IOException {
        ResultVO result = new ResultVO();
        PrintWriter out = null ;
        String token = request.getHeader("token");
        UserId String = request.getHeader ( "userId" );
         / ** your processing logic * /

        // return json format after the mode is returned interceptor intercepting 
        result.setStatus (203 );
        result.setMessage("Login verification failed, please login again");
        String jsonStr = BaccaratUtil.toJSon(result);
        
        response.setCharacterEncoding("UTF-8");  
        response.setContentType("application/json; charset=utf-8");
        
        out = response.getWriter();
        out.append(jsonStr);
        return false;
    }
    
     
}

JWTUtil.java

Package Comkbchcrtkutil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.internal.com.fasterxml.jackson.databind.ObjectMapper;
import com.baccarat.controller.UserController;
import com.baccarat.entity.User;

/**
 * @Todo JWT (JSON Web Token), usefully
 * @author Stephen
 * @Time 2019-10-11 12:12:04
 * / 
Public  class JWTUtil {

    private static Logger logger = Logger.getLogger(UserController.class);
    
    private static final String SECRET = "XX#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf>?N<:{LWPW";

    private static final String EXP = "exp";

    private static final String PAYLOAD = "payload";

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    /**
     * @Todo Encrypt, passing in an object and expiration date
     * @author Stephen
     * @Time 2019-10-11 12:12:44
     */
    public static <T> String sign(T object, long maxAge) {
        try {
            final JWTSigner signer = new JWTSigner(SECRET);
            final Map<String, Object> claims = new HashMap<String, Object>();
            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writeValueAsString(object);
            claims.put(PAYLOAD, jsonString);
            claims.put(EXP, System.currentTimeMillis() + maxAge);
            return signer.sign(claims);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @Todo Decrypt, passing in an encrypted token string and decrypted type
     * @author Stephen
     * @Time 2019-10-11 12:13:08
     * @param jwt,classT
     * @return T
     */
    public static <T> T unsign(String jwt, Class<T> classT) {
        final JWTVerifier verifier = new JWTVerifier(SECRET);
        try {
            final Map<String, Object> claims = verifier.verify(jwt);
            if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) {
                long exp = (Long) claims.get(EXP);
                long currentTimeMillis = System.currentTimeMillis();
                if (exp > currentTimeMillis) {
                    String json = (String) claims.get(PAYLOAD);
                    ObjectMapper objectMapper = new ObjectMapper();
                    return objectMapper.readValue(json, classT);
                }
            }
            return null;
        } catch (Exception e) {
            return null;
        }
    }

}

 

If in doubt, please note

Guess you like

Origin www.cnblogs.com/dzcici/p/11670952.html