token 생 성 및 token 검증

8226 단어 자바
토 큰 생 성
package org.zyyd.base.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;

import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Date;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtTokenUtil {
    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";
    private static final String ISS = "asd";

    //      3600 ,  1   
    private static final long EXPIRATION = 1800L;

    //               7 
    private static final long EXPIRATION_REMEMBER = 604800L;


    private static InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("jwt.jks");
    //       
    private static PrivateKey privateKey = null;
    private static PublicKey publicKey = null;
    static {
        //                
        try {
            KeyStore keyStore = KeyStore.getInstance("JKS");// java key store     
            keyStore.load(inputStream, "asdasd".toCharArray());
            privateKey = (PrivateKey) keyStore.getKey("jwt", "asdasd".toCharArray());// jwt               
            publicKey = keyStore.getCertificate("jwt").getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //    

    /**
     *     
     * @param json
    userName

     * @param isRememberMe
     * @return
     */
    public static String generateToken(JSONObject json, boolean isRememberMe) {
        long expiration = isRememberMe ? EXPIRATION_REMEMBER : EXPIRATION;
        return Jwts.builder()
                .setClaims(null)
                .setSubject(json.toJSONString())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .setIssuer(ISS)
                //.signWith(SignatureAlgorithm.HS512, salt)//        
                .signWith(SignatureAlgorithm.RS256, privateKey)
                .compact();
    }

    //  token   JSONObject
    public static JSONObject parseToken(String token) {
        JSONObject json = new JSONObject();
        String subject = null;
        try {
            Claims claims = getTokenBody(token);
            subject = claims.getSubject();
        } catch (Exception e) {

        }
        if(StringUtils.isNotBlank(subject)){
            json = JSON.parseObject(subject);
        }
        return json;
    }

    //      
    public static boolean isExpiration(String token){
        return getTokenBody(token).getExpiration().before(new Date());
    }

    private static Claims getTokenBody(String token){
        return Jwts.parser()
                .setSigningKey(publicKey)
                .parseClaimsJws(token)
                .getBody();
    }


}

차단 인증 토 큰


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.filter.OncePerRequestFilter;


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassName: LogFilter
 * @Description:
 * @author 
 * @date  2018/12/3 18:13
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);

    private AlUserService alUserService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        ApplicationContext ac =  WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
        alUserService = (AlUserService) ac.getBean("alUserServiceImpl");


        response.addHeader("Access-Control-Expose-Headers", JwtTokenUtil.TOKEN_HEADER);
        String authHeader = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
        String url=request.getRequestURI();
        if("/selfLearning/alApi/login".equals(url)){
            chain.doFilter(request, response);
        }else{

            if (request.getMethod().equals("OPTIONS")) {
                logger.info("          ..");
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,"+JwtTokenUtil.TOKEN_HEADER);
                return;
            }else {
                if (authHeader != null && authHeader.startsWith(JwtTokenUtil.TOKEN_PREFIX)) {
                    final String authToken = authHeader.substring(JwtTokenUtil.TOKEN_PREFIX.length());
                    JSONObject json= JwtTokenUtil.parseToken(authToken);
                    String username = (String) json.get("userName");
                    //   token                  
                    if (StringUtils.isNotBlank(username) && !JwtTokenUtil.isExpiration(authToken)) {
                        /*AlUser alUser = alUserService.getUserByUserName(username);

                        //         
                        if(StringUtils.isNotBlank(alUser.getUserId()) && "0".equals(alUser.getDeleteFlag())){

                        }else{
                            logger.info("     !");
                            Message message = new Message();
                            message.setStatus("0");
                            message.setMessage("     !");
                            response.getWriter().write(JSON.toJSONString(message));
                            return;
                        }*/


                    }else {
                        logger.info("    !");
                        response.setHeader("Content-type", "text/html;charset=UTF-8");
                        response.setCharacterEncoding("UTF-8");
                        response.setHeader("Access-Control-Allow-Origin", "*");
                        response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
                        response.setHeader("Access-Control-Max-Age", "3600");
                        response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization,token");
                        Message message = new Message();
                        message.setStatus(0);
                        message.setMessage("    !");
                        response.getWriter().write(JSON.toJSONString(message));
                        return ;
                    }
                }else{
                    Message message = new Message();
                    message.setStatus(0);
                    message.setMessage("    !");
                    response.getWriter().write(JSON.toJSONString(message));
                    return ;
                }
                chain.doFilter(request, response);
            }
        }
    }

}

좋은 웹페이지 즐겨찾기