查阅资料发现:Spring Boot与Spring Security整合后,不仅仅只是无法上传图片,只要是post请求,就会出现403拒绝访问
首先:403错误,表示资源不可用。服务器理解客户的请求,但拒绝处理它,通常由于服务器上文件或目录的权限设置导致的WEB访问错误。
了解了错误后,大概就是我用户权限不够吧。当我登录以后,以admin权限去操作post还是一样的错误。
于是去configure方法中找,看看是不是可以设置接收post操作:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45package cn.wzz.web; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) //开启security注解 public class WebSecurityConfig extends WebSecurityConfigurerAdapter{ @Bean @Override protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() //允许所有用户访问"/"和"/uploadFile" .antMatchers("/uploadFile").permitAll() //其他地址的访问均需验证权限 .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") //指定登录页是"/login" .defaultSuccessUrl("/list") //登录成功后默认跳转到"list" .permitAll() .and() .logout() .logoutSuccessUrl("/home") //退出登录后的默认url是"/home" .permitAll(); } @Override public void configure(WebSecurity web) throws Exception { //解决静态资源被拦截的问题 web.ignoring().antMatchers("/static/**"); } }
最终没有任何头绪。
于是怀疑框架自身的抑制,果然被我找到了:解决CsrfFilter与Rest服务Post方式的矛盾
具体就是框架内部防止CSRF(Cross-site request forgery跨站请求伪造)的发生,限制了除了get以外的大多数方法。
但是上述的解决方法是直接过滤掉指定的url,使其可以使用post以及其他被限制的方法,是一个漏洞!!!况且讲的是spring mvc 的配置文件方法。但是在Spring boot上还不知道怎么解决。
于是去看Spring security文档好了: Using Spring Security CSRF Protection
直接将csrf的功能关掉。。可以生效,但是项目的安全不也就没办法保障了嘛?继续往下看 ==》Include the CSRF Token
终于找到完美解决办法了:只要添加这个token,后台就会验证这个token的正确性,如果正确,则接受post访问。
8.但是又出现问题了。。我用的是thymeleaf模板:
Put CSRF into Headers in Spring 4.0.3 + Spring Security 3.2.3 + Thymeleaf 2.1.2
在stackoverflow上查到了。只要改一下:
这样,就可以完成自己的delete,put,post,patch方法的访问了
最后
以上就是大意花卷最近收集整理的关于Spring Boot与Spring Security整合后无法上传图片403的全部内容,更多相关Spring内容请搜索靠谱客的其他文章。
发表评论 取消回复