解决 Spring Security 常见问题

以下问题都是由于粗心大意造成的/(ㄒoㄒ)/~~,同学,敲代码一定要仔细呀

未创建 Bean

问题:无法创建 ‘springSecurityFilterChain’

1
No bean named 'springSecurityFilterChain' is defined.

解决:

  1. 首先看控制台的错误
  2. 发现启动没加载 spring-security.xml
  3. *找到 web.xml,把 CoutextLoaderListener 改为 ContextLoaderListener *
1
2
3
4
<listener>
/* <listener-class>org.springframework.web.context.CoutextLoaderListener</listener-class> */
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

无效参数

问题:非法参数,重复配置了 ‘/**’

1
java.lang.IllegalArgumentException: A universal match pattern (‘/**’) is defined before other patterns in the filter chain, causing them to be ignored.

解决:

  1. 首先看控制台的错误
1
2
3
// 同时加载了两个配置,但我的源码里只有一个配置鸭
common_cas/spring-security.xml
web_center/spring-security.xml
  1. 再看项目的打包文件,果然有 spring-security.xml
  2. 输入如下命令
1
mvn clean install
  1. 启动 tomcat ,一切正常

请求错误

开始我没有看这个警告,一般我只看 ‘Error’,(lll¬ω¬),但就是因为不仔细看,才花了 1h 才发现这个错误

问题:提交 JSON 返回401,提示未授权

1
2
WARN 5820 --- [io-9001-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected character ('"' (code 34)): was expecting comma to separate Object entries; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('"' (code 34)): was expecting comma to separate Object entries
at [Source: (PushbackInputStream); line: 3, column: 6]]

解决:

  1. 请求/user/login,提示未授权,很明显,后端没有对我授权
1
2
3
4
5
Status:401
{
"error": "unauthorized",
"error_description": "Full authentication is required to access this resource"
}
  1. 于是 DEBUG,打断点,可是请求不到断点
  2. 这时怀疑没扫描到 Controller,给 Controller 新增方法吧
1
2
3
4
@GetMapping("demo")
public String demo() {
return "demo";
}
  1. OK,请求成功,再次 POST 请求还是返回 401,奇怪,试试关掉 csrf
1
http.csrf().disable();
  1. 再次请求还是返回 401,看了看 JSON 格式,好吧,原来 JSON 格式写错了
1
2
3
4
{
"username": "pan176"
"password": "123456"
}
  1. 你发现了吗?少了一个逗号,正确格式:
1
2
3
4
{
"username": "pan176",
"password": "123456"
}

评论