vue+springboot+jwt

springboot解决跨域

@Configuration
public class CORSConfig {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins(ALL)
                        .allowedMethods(ALL)
                        .allowedHeaders(ALL)
                        .allowCredentials(true);
            }
        };
    }

}

spring登录拦截器,不知道是什么问题,前端发送过来的请求都变成了option请求,获取到的token也是空值,返回给前端的response也是空值

public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static final PathMatcher pathMatcher = new AntPathMatcher();

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

        if(!request.getRequestURI().contains("admin"))
        {
          
            try {
                if (isProtectedUrl(request)) {
                    String token = request.getHeader("token");
                    System.out.println("token:"+token);
                    // 检查jwt令牌, 如果令牌不合法或者过期, 里面会直接抛出异常, 下面的catch部分会直接返回
                    JwtUtil.validateToken(token);
                }
            } catch (Exception e) {
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            }
            // 如果jwt令牌通过了检测, 那么就把request传递给后面的RESTful api
            filterChain.doFilter(request, response);
        }
        filterChain.doFilter(request, response);

    }

    // 我们只对地址 /api 开头的api检查jwt. 不然的话登录/login也需要jwt
    private boolean isProtectedUrl(HttpServletRequest request) {
        return pathMatcher.match("/admin/api/**", request.getServletPath());
    }

最终还是没有办法,就退而求其次,写了一个baseController,虽然问题解决了,但是还是没有正面解决,谁有好的办法

//登录
    public  Map<String, Object>  errorMap()
    {
         
          Map<String, Object>  dataMap=new HashMap<>();
          
          dataMap.put("code", 401);
          dataMap.put("token", "token无效,请重新登录");
          return dataMap;
        
    }
    
    //登录验证
    public  Boolean loginValidate(HttpServletRequest request)
    {
        String token = request.getHeader("Authorization");
        System.out.println("token:"+token);
         Boolean flag =JwtUtil.validateToken(token);
         return flag;
    }
    

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值