• 前后端分离,获取token,验证登陆是否失效


    maven依赖

    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>2.2.0</version>
    </dependency>
    public class JwtUtils {
    
        /**
         * 密钥
         */
        private static  final String SECRET="xxxx";
        /**
         * 默认字段key:exp
         */
        private static final String EXP="exp";
        /**
         * 默认字段key:payload
         */
        private static final String PAYLOAD="payload";
    
        /**
         * 加密
         * @param object 加密数据
         * @param maxTime 有效期(毫秒数)
         * @param <T>
         * @return
         */
        public static <T> String encode(T object,long maxTime){
            try{
                final JWTSigner signer=new JWTSigner(SECRET);
                final Map<String ,Object> data=new HashMap<>(10);
                ObjectMapper objectMapper=new ObjectMapper();
                String jsonString=objectMapper.writeValueAsString(object);
                data.put(PAYLOAD,jsonString);
                data.put(EXP,System.currentTimeMillis()+maxTime);
                return signer.sign(data);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    
        /**
         * 数据解密
         * @param jwt 解密数据
         * @param tClass 解密类型
         * @param <T>
         * @return
         */
        public static <T> T decode(String jwt,Class<T> tClass) {
            final JWTVerifier jwtVerifier = new JWTVerifier(SECRET);
            try {
                final Map<String, Object> data = jwtVerifier.verify(jwt);
                //判断数据是否超时或者符合标准
                if (data.containsKey(EXP) && data.containsKey(PAYLOAD)) {
                    long exp = (long) data.get(EXP);
                    long currentTimeMillis = System.currentTimeMillis();
                    if (exp > currentTimeMillis) {
                        String json = (String) data.get(PAYLOAD);
                        ObjectMapper objectMapper = new ObjectMapper();
                        return objectMapper.readValue(json, tClass);
                    }
                }
                return null;
            } catch (Exception e) {
                //e.printStackTrace();
                return null;
            }
        }
    
        //解密token取出userId
        public static <T> T updateDecode(String jwt,Class<T> tClass){
            final JWTVerifier jwtVerifier = new JWTVerifier(SECRET);
            try {
                final Map<String, Object> data = jwtVerifier.verify(jwt);
                        String json = (String) data.get(PAYLOAD);
                        ObjectMapper objectMapper = new ObjectMapper();
                        return objectMapper.readValue(json, tClass);
            } catch (Exception e) {
                //e.printStackTrace();
                return null;
            }
        }
        public static void main(String[] args) throws InterruptedException {
    //        有效期10秒
    //        加密:
    //        TestCenterAdministratorsVO test = new TestCenterAdministratorsVO();
    //        test.setId(1L);
    //        test.setLoginName("sa");
    //        String token=encode(test,1000000);
    //        System.out.println("TOKEN======="+token);
    //        //Thread.sleep(10000);
    ////      解密
    //        TestCenterAdministratorsVO user=decode(token,TestCenterAdministratorsVO.class);
    //        System.out.println(user.getId()+user.getLoginName());
            //removeDecode("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NDcwODkwNTYxNDgsInBheWxvYWQiOiJ7XCJpZFwiOjEsXCJuYW1lXCI6bnVsbCxcInBob25lTnVtYmVyXCI6bnVsbCxcImxvZ2luTmFtZVwiOlwic2FcIixcInNlcmlhbE51bWJlclwiOm51bGwsXCJ0eXBlXCI6bnVsbCxcInRlc3RDZW50ZXJJZFwiOm51bGwsXCJvcmdhbml6YXRpb25JZFwiOm51bGwsXCJtYWluU2l0ZUFkbWluXCI6ZmFsc2UsXCJhZG1pblwiOmZhbHNlLFwib3JnYW5pemF0aW9uTmFtZVwiOm51bGx9In0.FgYm4wSDhkZukqlRukjwvxQ1BM746AWQfCmGucMP3pc");
        updateDecode("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NDcwMTgxNTU4OTYsInBheWxvYWQiOiJ7XCJpZFwiOjIwMTAwMDAzMyxcIm5hbWVcIjpcIuW6numTtuaYjFwiLFwicGhvbmVOdW1iZXJcIjpudWxsLFwibG9naW5OYW1lXCI6XCJwYW5neWluY2hhbmdcIixcInNlcmlhbE51bWJlclwiOm51bGwsXCJ0eXBlXCI6XCJNQUlOU0lURUFETUlOXCIsXCJ0ZXN0Q2VudGVySWRcIjo3OSxcIm9yZ2FuaXphdGlvbklkXCI6XCIwMDFcIixcIm1haW5TaXRlQWRtaW5cIjp0cnVlLFwiYWRtaW5cIjpmYWxzZSxcIm9yZ2FuaXphdGlvbk5hbWVcIjpudWxsfSJ9.yrYlU4djPPQyu1mneQgkVgLCEQiJ2pKkyX8EVw0NcY8",TestCenterAdministratorsVO.class);
    
        }
    }

    跨域设置拦截器

    import com.alibaba.fastjson.JSONObject;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    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;
    
    /**
     * Created with IDEA
     * author:QinWei
     * Date:2019/1/8
     * Time:16:15
     */
    public class AjaxFilter implements Filter {
    
        @Override
        public void destroy() {
    
        }
    
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res,
                             FilterChain chain) throws IOException, ServletException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) res;
            //禁止首页访问
            String url = request.getRequestURI();
            if("/".equals(url)){
                return;
            }
            // 指定允许其他域名访问
            response.setHeader("Access-Control-Allow-Origin", "*");
        // 响应类型
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");
        // 响应头设置
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token");
            chain.doFilter(req, res);
        }
    
        @Override
        public void init(FilterConfig arg0) throws ServletException {
        }
    }

    web.xml

    <filter>
            <filter-name>ajaxFilter</filter-name>
            <filter-class>*.*.*.web.servlet.barcode.AjaxFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>ajaxFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>

     拦截token过滤器,包含获取spring--bean手动注入

    response .setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            String actionName = context.getActionInvocation().getProxy().getActionName();
            String url = request.getRequestURI();
            ServletContext application = ServletActionContext.getServletContext();
            WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(application);
            this.testCenterService = (TestCenterService)ctx.getBean("testCenterService");
            if(!url.equals("/login")){
                //悠闲判断是否为空或者时间是否失效
                String token = request.getParameter("token");
                TestCenterAdministratorsVO user = JwtUtils.decode(token, TestCenterAdministratorsVO.class);
                if(null==token||"".equals(token)||null==user){
                    out.print(Message.error(0,"token不合法!"));
                    return null;
                }else{
                    try {
                        //再次判断数据库状态
                            TestCenterAdministratorsVO users = JwtUtils.updateDecode(token, TestCenterAdministratorsVO.class);
                           String tokens = testCenterService.scheckToken(token,users.getId());
                            if(null==tokens){
                                out.print(Message.error(0,"token不合法!"));
                                return null;
                        }
                    }catch (Exception e){
                        out.print(Message.error());
                        return null;
                    }
                }
            }

    加群:687942640

    微信扫描公众号

  • 相关阅读:
    Unix下可用的五种 I/O 模型
    mysql查看死锁和解除锁
    MySQL按日期分组并统计截止当前时间的总数(实例教程)
    Java对象为啥要实现Serializable接口
    Linux下java进程CPU占用率高分析方法(二)
    Linux下java进程CPU占用率高分析方法(一)
    futex的设计与实现
    Java 理论与实践-非阻塞算法简介
    Java Web J2EE下的两大框架SSH和SSM对比
    Canvas文本操作
  • 原文地址:https://www.cnblogs.com/qwlscn/p/11495368.html
Copyright © 2020-2023  润新知