Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

路由拦截鉴权 报错 NestedServletException #276

Closed
iehong opened this issue Jul 4, 2022 · 67 comments
Closed

路由拦截鉴权 报错 NestedServletException #276

iehong opened this issue Jul 4, 2022 · 67 comments

Comments

@iehong
Copy link

iehong commented Jul 4, 2022

使用版本:

1.30

报错信息:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is cn.dev33.satoken.exception.NotLoginException: 未能读取到有效Token

希望结果:

不报错

复现步骤:

public void addInterceptors(InterceptorRegistry registry) {
    // 注册 Sa-Token 的路由拦截器
    registry.addInterceptor(new SaRouteInterceptor())
        .addPathPatterns("/**")
        .excludePathPatterns("/user/register", "/user/login");
  }

类似 https://blog.csdn.net/qq_61317175/article/details/120784746

@iehong
Copy link
Author

iehong commented Jul 4, 2022

image

@iehong
Copy link
Author

iehong commented Jul 4, 2022

registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
    }))

改成这样可以

@click33
Copy link
Collaborator

click33 commented Jul 4, 2022

访问的什么接口

@iehong
Copy link
Author

iehong commented Jul 4, 2022

访问的什么接口

获取用户信息

@click33
Copy link
Collaborator

click33 commented Jul 4, 2022

路由是啥

@iehong
Copy link
Author

iehong commented Jul 4, 2022

image
还没上线 /api/user/info

@click33
Copy link
Collaborator

click33 commented Jul 4, 2022

你添加了登录校验拦截器,只排除了:"/user/register", "/user/login"
然后访问的: /api/user/info
被校验出:会话未登录
这不很正常吗

@iehong
Copy link
Author

iehong commented Jul 4, 2022

但是是登录状态的 /api/user/info这个接口需要登录才能访问 报错是不正常的 改成

registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
    }))

正常

@click33
Copy link
Collaborator

click33 commented Jul 4, 2022

从报错来看,是前端没有提交token

排查一下: 1、登录时有没有返回token 2、token有没有写入到前端cookie或localStore中 3、后续请求时,token有没有提交到后端

@iehong
Copy link
Author

iehong commented Jul 4, 2022

提交了
改成

registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
}))
正常的,应该是框架的问题

@click33
Copy link
Collaborator

click33 commented Jul 4, 2022

你改成
registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
}))

就没有校验了,没有校验当然就不报错了

仔细看文档:
image

@iehong
Copy link
Author

iehong commented Jul 4, 2022

就算没提交token也不能报NestedServletException,应该报NotLoginException,报NestedServletException就是框架的锅

@click33
Copy link
Collaborator

click33 commented Jul 4, 2022

你有写全局异常拦截处理器吗

@iehong
Copy link
Author

iehong commented Jul 4, 2022

写了

@ControllerAdvice
public class AllExceptionHandler {

  @ExceptionHandler(Exception.class)
  @ResponseBody
  public Result doException(Exception ex) {
    ex.printStackTrace();
    return Result.fail(500, "系统异常");
  }

  @ExceptionHandler(NotLoginException.class)
  @ResponseBody
  public Result doNotLoginException(NotLoginException ex) {
    return Result.fail(401, ex.getMessage());
  }
}

@click33
Copy link
Collaborator

click33 commented Jul 4, 2022

你在浏览器f12看一下控制台,截图一下发送请求时的 token 参数我看看

@iehong
Copy link
Author

iehong commented Jul 4, 2022

image

@click33
Copy link
Collaborator

click33 commented Jul 4, 2022

后端的 yml 配置中,token-name 参数有改动吗

@iehong
Copy link
Author

iehong commented Jul 4, 2022

image

@click33
Copy link
Collaborator

click33 commented Jul 4, 2022

你打印一下 StpUtil.getTokenValue() 看看能成功获取到前端提交的 token 吗

@iehong
Copy link
Author

iehong commented Jul 4, 2022

@iehong
Copy link
Author

iehong commented Jul 4, 2022

框架的锅,别再说我没传token了

@Abandoned9
Copy link

有没有可能真的是你有问题?
首先,你访问的是/api/user/info
你的拦截器里面写的是

public void addInterceptors(InterceptorRegistry registry) {
    // 注册 Sa-Token 的路由拦截器
    registry.addInterceptor(new SaRouteInterceptor())
        .addPathPatterns("/**")
        .excludePathPatterns("/user/register", "/user/login");
  }

excludePathPatterns是放行的路由地址,你只放了/user/register,你的/api前缀呢?
其次,你说改成下面的代码就行

registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
}))

你真的懂上面写法的含义吗?
再有,你仔细看看上面的错误类型,你看报错信息里面写的不就是NotLoginException吗?只是被包了一层NestedServletException

然后你上面发的那个csdn的博客那博主怕是自己都没写明白,属于是俩臭皮匠,顶不了一个臭皮匠了

@iehong
Copy link
Author

iehong commented Jul 4, 2022

有没有可能真的是你有问题? 首先,你访问的是/api/user/info 你的拦截器里面写的是

public void addInterceptors(InterceptorRegistry registry) {
    // 注册 Sa-Token 的路由拦截器
    registry.addInterceptor(new SaRouteInterceptor())
        .addPathPatterns("/**")
        .excludePathPatterns("/user/register", "/user/login");
  }

excludePathPatterns是放行的路由地址,你只放了/user/register,你的/api前缀呢? 其次,你说改成下面的代码就行

registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
}))

你真的懂上面写法的含义吗? 再有,你仔细看看上面的错误类型,你看报错信息里面写的不就是NotLoginException吗?只是被包了一层NestedServletException

然后你上面发的那个csdn的博客那博主怕是自己都没写明白,属于是俩臭皮匠,顶不了一个臭皮匠了

没有可能,是框架的锅
改成

registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
}))
正常的

@Abandoned9
Copy link

image

还有,你这错误是CORS错误,你给我好好的先弄明白跨域问题再说?

@Abandoned9
Copy link

你知道你上面那么写为什么正常了吗?
你上面那种写法跟你把sa-token从你的maven里删掉是一个意思,你要真不明白你别用了

@iehong
Copy link
Author

iehong commented Jul 4, 2022

image
这样写 sa-token 是起作用的

@iehong
Copy link
Author

iehong commented Jul 4, 2022

@Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
        .allowedOriginPatterns("*")
        .allowedMethods("*");
  }

跨域

@iehong
Copy link
Author

iehong commented Jul 4, 2022

大家踩这说脏话,没素质,秀优越的人

@iehong
Copy link
Author

iehong commented Jul 4, 2022

image
apis是写在这里的

@Abai-LL
Copy link

Abai-LL commented Jul 4, 2022

image

CORS跨域开了吗

@iehong
Copy link
Author

iehong commented Jul 4, 2022

sa-token:
  # jwt秘钥
  jwt-secret-key: 1qaz*****
  # token 名称 (同时也是cookie名称)
  token-name: Authorization
  # token 有效期,单位s 默认30天, -1代表永不过期
  timeout: 2592000
  # token 临时有效期 (指定时间内无操作就视为token过期) 单位: 秒
  activity-timeout: -1
  # 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录)
  is-concurrent: true
  # 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token)
  is-share: false
  # token风格
  token-style: uuid
  # 是否输出操作日志
  is-log: false

@click33
Copy link
Collaborator

click33 commented Jul 4, 2022

前端提交了,但后端却没获取到,看看后端接受到token参数了吗

打印 StpUtil.getTokenValue() 看看有值吗
然后再打印 SaHolder.getRequest().getHeader("Authorization") 看看有值吗

@iehong
Copy link
Author

iehong commented Jul 4, 2022

registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> { console.log(StpUtil.getTokenValue()) })) 这样就正常了 只有写在这里面,不然报没有剩下文的错

@iehong
Copy link
Author

iehong commented Jul 4, 2022

package com.yyt.jdfyakfp.config;

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;

import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpLogic;

@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
  // Sa-Token 整合 jwt (Simple 简单模式)
  @Bean
  public StpLogic getStpLogicJwt() {
    return new StpLogicJwtForSimple();
  }

  // 注册拦截器
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    // 注册 Sa-Token 的路由拦截器
    registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
    }))
        .addPathPatterns("/**")
        .excludePathPatterns("/user/register", "/user/login");
  }

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
        .allowedOriginPatterns("*")
        .allowedMethods("*");
  }
}

@click33
Copy link
Collaborator

click33 commented Jul 4, 2022

那你倒是说一下,这两个打印有值吗

打印 StpUtil.getTokenValue() 看看有值吗
然后再打印 SaHolder.getRequest().getHeader("Authorization") 看看有值吗

@AppleOfGray
Copy link
Collaborator

当前问题异议很大, 如果还是无法解决,建议提供能复现当前bug的最小开发项目压缩包或开源的项目地址(请务必删除私人信息), 我们将在本地测试后再提供相关指导意见.

@iehong
Copy link
Author

iehong commented Jul 5, 2022

image
postman 测试室可以的,是不是前端请求头有点问题

@click33
Copy link
Collaborator

click33 commented Jul 5, 2022

我知道你前端提交 token 了,但是后端框架没有接受到这个参数,所以我想知道在 SpringMVC 层面解析到这个参数了吗,需要你打印一下这两句代码来确认一下:

打印 StpUtil.getTokenValue() 看看有值吗
然后再打印 SaHolder.getRequest().getHeader("Authorization") 看看有值吗

希望你可以测试一下提供结果

@iehong
Copy link
Author

iehong commented Jul 5, 2022

registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
      Console.log(StpUtil.getTokenValue());
      Console.log(SaHolder.getRequest().getHeader("Authorization"));
    }))

image

@iehong
Copy link
Author

iehong commented Jul 5, 2022

写这个 (req, res, handler) -> 前端就不会卡住的
image
三次请求

@click33
Copy link
Collaborator

click33 commented Jul 5, 2022

再多打印几个我看看

Console.log(StpUtil.getTokenName());
		Console.log(StpUtil.getTokenValue());
	    Console.log(SaHolder.getRequest().getHeader("Authorization"));
		Console.log(SaManager.getConfig());

@iehong
Copy link
Author

iehong commented Jul 5, 2022

2022-07-05 11:11:34.875  INFO 6628 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 4 ms
2022-07-05 11:11:35.904  INFO 6628 --- [nio-8080-exec-1] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
Authorization
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiS0szR25zQ0xIemFsRDhYUlU1UzE0OWpiWXFpRE5EdVkifQ.mLj5nSa9zvp_NLkS6hNWmITFt403yffeyQWkXrP31vY
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiS0szR25zQ0xIemFsRDhYUlU1UzE0OWpiWXFpRE5EdVkifQ.mLj5nSa9zvp_NLkS6hNWmITFt403yffeyQWkXrP31vY
SaTokenConfig [tokenName=Authorization, timeout=2592000, activityTimeout=-1, isConcurrent=true, isShare=false, maxLoginCount=12, isReadBody=true, isReadHead=true, isReadCookie=true, tokenStyle=uuid, dataRefreshPeriod=30, tokenSessionCheckLogin=true, autoRenew=true, tokenPrefix=null, isPrint=true, isLog=false, jwtSecretKey=1qaz2wsx3edc, idTokenTimeout=86400, basic=, currDomain=null, checkIdToken=false, cookie=SaCookieConfig [domain=null, path=null, secure=false, httpOnly=false, sameSite=null]]
Authorization
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiS0szR25zQ0xIemFsRDhYUlU1UzE0OWpiWXFpRE5EdVkifQ.mLj5nSa9zvp_NLkS6hNWmITFt403yffeyQWkXrP31vY
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiS0szR25zQ0xIemFsRDhYUlU1UzE0OWpiWXFpRE5EdVkifQ.mLj5nSa9zvp_NLkS6hNWmITFt403yffeyQWkXrP31vY
SaTokenConfig [tokenName=Authorization, timeout=2592000, activityTimeout=-1, isConcurrent=true, isShare=false, maxLoginCount=12, isReadBody=true, isReadHead=true, isReadCookie=true, tokenStyle=uuid, dataRefreshPeriod=30, tokenSessionCheckLogin=true, autoRenew=true, tokenPrefix=null, isPrint=true, isLog=false, jwtSecretKey=1qaz2wsx3edc, idTokenTimeout=86400, basic=, currDomain=null, checkIdToken=false, cookie=SaCookieConfig [domain=null, path=null, secure=false, httpOnly=false, sameSite=null]]
Authorization
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiS0szR25zQ0xIemFsRDhYUlU1UzE0OWpiWXFpRE5EdVkifQ.mLj5nSa9zvp_NLkS6hNWmITFt403yffeyQWkXrP31vY
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiS0szR25zQ0xIemFsRDhYUlU1UzE0OWpiWXFpRE5EdVkifQ.mLj5nSa9zvp_NLkS6hNWmITFt403yffeyQWkXrP31vY
SaTokenConfig [tokenName=Authorization, timeout=2592000, activityTimeout=-1, isConcurrent=true, isShare=false, maxLoginCount=12, isReadBody=true, isReadHead=true, isReadCookie=true, tokenStyle=uuid, dataRefreshPeriod=30, tokenSessionCheckLogin=true, autoRenew=true, tokenPrefix=null, isPrint=true, isLog=false, jwtSecretKey=1qaz2wsx3edc, idTokenTimeout=86400, basic=, currDomain=null, checkIdToken=false, cookie=SaCookieConfig [domain=null, path=null, secure=false, httpOnly=false, sameSite=null]]

@click33
Copy link
Collaborator

click33 commented Jul 5, 2022

目前看配置方面没啥问题,你再加俩我看看

Console.log(StpUtil.getTokenName());
		Console.log(StpUtil.getTokenValue());
	    Console.log(SaHolder.getRequest().getHeader("Authorization"));
		Console.log(SaManager.getConfig());
		Console.log(SaHolder.getRequest().getRequestPath());
		Console.log(SaHolder.getRequest().getMethod());

@iehong
Copy link
Author

iehong commented Jul 5, 2022


2022-07-05 11:15:31.707  WARN 6628 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [cn.dev33.satoken.exception.NotLoginException: 未能读取到有效Token]
2022-07-05 11:15:54.307  INFO 6628 --- [nio-8080-exec-2] com.alibaba.druid.pool.DruidDataSource   : {dataSource-2} inited
Authorization
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiRDJ5TGFQeHBFblJOdmg3T2FsVTExdHliUkpNUG9GZ2MifQ.jtD8sBxm3wEfICGU0YqEnoRDILLVomx-ioAZxiHgx48
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiRDJ5TGFQeHBFblJOdmg3T2FsVTExdHliUkpNUG9GZ2MifQ.jtD8sBxm3wEfICGU0YqEnoRDILLVomx-ioAZxiHgx48
SaTokenConfig [tokenName=Authorization, timeout=2592000, activityTimeout=-1, isConcurrent=true, isShare=false, maxLoginCount=12, isReadBody=true, isReadHead=true, isReadCookie=true, tokenStyle=uuid, dataRefreshPeriod=30, tokenSessionCheckLogin=true, autoRenew=true, tokenPrefix=null, isPrint=true, isLog=false, jwtSecretKey=1qaz2wsx3edc, idTokenTimeout=86400, basic=, currDomain=null, checkIdToken=false, cookie=SaCookieConfig [domain=null, path=null, secure=false, httpOnly=false, sameSite=null]]
/user/info
GET
Authorization
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiRDJ5TGFQeHBFblJOdmg3T2FsVTExdHliUkpNUG9GZ2MifQ.jtD8sBxm3wEfICGU0YqEnoRDILLVomx-ioAZxiHgx48
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiRDJ5TGFQeHBFblJOdmg3T2FsVTExdHliUkpNUG9GZ2MifQ.jtD8sBxm3wEfICGU0YqEnoRDILLVomx-ioAZxiHgx48
SaTokenConfig [tokenName=Authorization, timeout=2592000, activityTimeout=-1, isConcurrent=true, isShare=false, maxLoginCount=12, isReadBody=true, isReadHead=true, isReadCookie=true, tokenStyle=uuid, dataRefreshPeriod=30, tokenSessionCheckLogin=true, autoRenew=true, tokenPrefix=null, isPrint=true, isLog=false, jwtSecretKey=1qaz2wsx3edc, idTokenTimeout=86400, basic=, currDomain=null, checkIdToken=false, cookie=SaCookieConfig [domain=null, path=null, secure=false, httpOnly=false, sameSite=null]]
/workspace/info
GET
Authorization
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiRDJ5TGFQeHBFblJOdmg3T2FsVTExdHliUkpNUG9GZ2MifQ.jtD8sBxm3wEfICGU0YqEnoRDILLVomx-ioAZxiHgx48
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsInJuU3RyIjoiRDJ5TGFQeHBFblJOdmg3T2FsVTExdHliUkpNUG9GZ2MifQ.jtD8sBxm3wEfICGU0YqEnoRDILLVomx-ioAZxiHgx48
SaTokenConfig [tokenName=Authorization, timeout=2592000, activityTimeout=-1, isConcurrent=true, isShare=false, maxLoginCount=12, isReadBody=true, isReadHead=true, isReadCookie=true, tokenStyle=uuid, dataRefreshPeriod=30, tokenSessionCheckLogin=true, autoRenew=true, tokenPrefix=null, isPrint=true, isLog=false, jwtSecretKey=1qaz2wsx3edc, idTokenTimeout=86400, basic=, currDomain=null, checkIdToken=false, cookie=SaCookieConfig [domain=null, path=null, secure=false, httpOnly=false, sameSite=null]]
/error
GET

@iehong
Copy link
Author

iehong commented Jul 5, 2022

加上(req, res, handler) ->这个是不报错的

@click33
Copy link
Collaborator

click33 commented Jul 5, 2022

加上(req, res, handler) ->这个是不报错,
是因为加上这个后,相当于把 Sa-Token 的鉴权给关闭了,关闭了当然就不会报错了

@click33
Copy link
Collaborator

click33 commented Jul 5, 2022

这里为啥有个 /error
你有访问这个接口吗
image

@iehong
Copy link
Author

iehong commented Jul 5, 2022

没有,估计是sa-token访问的

@click33
Copy link
Collaborator

click33 commented Jul 5, 2022

sa-token 是个鉴权框架,不是个http请求框架,不会发送请求

@click33
Copy link
Collaborator

click33 commented Jul 5, 2022

你弄个复现的demo上传一下吧,我下载到本地调试一下

@AppleOfGray
Copy link
Collaborator

关于这个博客, 我作出了相关回复: https://blog.csdn.net/qq_61317175/article/details/120784746

@click33
Copy link
Collaborator

click33 commented Jul 5, 2022

或者你加一下微信、qq群,我给你远程

@iehong
Copy link
Author

iehong commented Jul 5, 2022

image

@AppleOfGray
Copy link
Collaborator

1群和2群总人数都是快2千了,
大部分开发者都是会使用satoken框架的,
所以平时闲聊也就不足为怪了.
如果有技术问题他们还是会优先回答的.
开放新群的目的就是给新人一个融入的机会,
人数少回答问题也方便.

@iehong iehong closed this as completed Jul 5, 2022
@qzmer1104
Copy link

qzmer1104 commented Jul 6, 2022

@Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
        .allowedOriginPatterns("*")
        .allowedMethods("*");
  }

@OverRide public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("") .allowedMethods(""); } 开了

很简单的问题,https://blog.csdn.net/huangyaa729/article/details/103893660

cors尽量不要用此方式添加如果你们都不看源码的情况,可以用过滤器加,加个config的bean就好了

@Bean
    public FilterRegistrationBean corsFilter() {

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(true);

        config.addAllowedOrigin("*");

        config.addAllowedHeader(CorsConfiguration.ALL);
        config.addAllowedMethod(CorsConfiguration.ALL);

        source.registerCorsConfiguration("/**", config);

        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));

        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);

        return bean;
    }

@yixiaco
Copy link

yixiaco commented Jul 7, 2022

CORS就跨域嘛,前端的跨域解决了就剩下后端的跨域要解决了,这个是springWeb的拦截器负责的,也许你需要声明一个CorsFilter的Bean

/**
 * 跨域配置
 */
@Bean
public CorsFilter corsFilter() {
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    // 设置访问源地址
    config.addAllowedOriginPattern("*");
    // 设置访问源请求头
    config.addAllowedHeader("*");
    // 设置访问源请求方法
    config.addAllowedMethod("*");
    // 有效期 1800秒
    config.setMaxAge(1800L);
    // 添加映射路径,拦截一切请求
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", config);
    // 返回新的CorsFilter
    return new CorsFilter(source);
}

这个是摘取RuoYi-Vue-Plus里面的配置

@Enaium
Copy link

Enaium commented Nov 4, 2022

controller有异常的时候,并不会抛出controller的异常,只会抛出未能读取到有效Token这个异常

@tjlizz
Copy link

tjlizz commented Feb 2, 2023

这里为啥有个 /error 你有访问这个接口吗 image

我遇到过这样的问题,前端传的请求是带token的没问题,但是方法执行过程中出现异常,然后就访问 /error,这个时候就报错未能读取到有效Token

image

@Huzhengtao
Copy link

Huzhengtao commented Feb 2, 2023

你这里面总共就两个问题 第一个路由拦截路径写的不对 另外就是你没传token checkLogin方法你都调用了 日志写的多明白

public void addInterceptors(InterceptorRegistry registry) {
    // 注册 Sa-Token 的路由拦截器
    registry.addInterceptor(new SaRouteInterceptor())
        .addPathPatterns("/**")
        .excludePathPatterns("/user/register", "/user/login");
  }

上面的代码显示截取/**所有路径,但是放行/user/register/user/login/api/user/login和你/user/login有什么关系?有一个寄存吧关系

戾气太重,这是框架和跨域的冲突问题。spring使用注册WebMvcConfigurer的addCorsMappings方法的方式做跨域会导致options预检请求也会检测token,但options预检请求不会携带自定义header,就会抛出异常,然后spring会把请求重定向到/error。换成注册CorsFilter来做跨域就会正常了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests