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
{
Map
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;
}