第6讲后端鉴权拦截器实现

后端鉴权拦截器实现

package com.java1234.interceptor;

import com.java1234.util.JwtUtils;
import com.java1234.util.StringUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 鉴权拦截器
 * @author java1234_小锋
 * @site www.java1234.com
 * @company Java知识分享网
 * @create 2021-01-29 14:11
 */
public class SysInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path=request.getRequestURI();
        System.out.println(path);
        if(handler instanceof HandlerMethod){
            String token = request.getHeader("token");
            System.out.println("token:"+token);
            if(StringUtil.isEmpty(token)){
                System.out.println("token为空!");
                throw new RuntimeException("签名验证不存在");
            }else{
                Claims claims = JwtUtils.validateJWT(token).getClaims();
                if(claims!=null){
                    System.out.println("验证成功");
                    return true;
                }else{
                    System.out.println("验证失败");
                    throw new RuntimeException("签名失败");
                }
            }
        }else{
            return true;
        }
    }


}

新建WebAppConfigurer

package com.java1234.config;

import com.java1234.interceptor.SysInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author java1234_小锋 (公众号:java1234)
 * @site www.java1234.vip
 * @company 南通小锋网络科技有限公司
 */
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {

    @Bean
    public SysInterceptor sysInterceptor(){
        return new SysInterceptor();
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        String[] patterns=new String[]{"/user/wxlogin","/image/**"};
        registry.addInterceptor(sysInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns(patterns);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE","OPTIONS")
                .maxAge(3600);
    }
}

你可能感兴趣的:(uniapp微信小程序投票系统,json)