Spring Boot与Spring Security整合后无法上传图片403

查阅资料发现:Spring Boot与Spring Security整合后,不仅仅只是无法上传图片,只要是post请求,就会出现403拒绝访问

 

首先:403错误,表示资源不可用。服务器理解客户的请求,但拒绝处理它,通常由于服务器上文件或目录的权限设置导致的WEB访问错误。

了解了错误后,大概就是我用户权限不够吧。当我登录以后,以admin权限去操作post还是一样的错误。

于是去configure方法中找,看看是不是可以设置接收post操作:

package 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方法的访问了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值