Spring security - post请求不了,报错:405错误

主要问题在:SecurityConfig 文件中的配置存在问题,需要把:csrf防护给关闭掉(security默认是打开的)

以下是详细代码实例:
package com.zsdag.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**

  • Spring Security 登录,认证,权限
    */
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    // super.configure(http);

     //访问角色说明:
     // 1.信息系统类统计                     /Information
     // 2.馆藏类统计                        /Center
     // 3.室藏类统计                        /Room
     // 4.网站、微博、参观展览人次统计        /ThirdPlatform
     // 5.中山档案大数据                    /BigData
    
     //1.制定请求的授权规则
     http.authorizeRequests()
             .antMatchers("/","index","/login","/login-error","/401","/css/**","/js/**","/webjars/**","/asserts/**").permitAll()
             .antMatchers("/Information/**").hasRole("VIP1")
             .antMatchers("/Center/**").hasRole("VIP2")
             .antMatchers("/Room/**").hasRole("VIP3")
             .antMatchers("/ThirdPlatform/**").hasRole("VIP4")
             .antMatchers("/BigData/**").hasRole("VIP5")
             .anyRequest().authenticated()
             .and()
             .formLogin().loginPage("/login").failureUrl("/login-error")
             .and()
             .exceptionHandling().accessDeniedPage("/401")
             .and().csrf().disable();//禁用csrf,否则post方法无法访问
    
     //2.开启自动配置的登录功能
    

// http.formLogin().usernameParameter(“userName”).passwordParameter(“passWord”)
// .loginPage("/userLogin/loginPage");

    http.logout().logoutSuccessUrl("/");

}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    //访问角色说明:
    // 1.信息系统类统计                     /Information
    // 2.馆藏类统计                        /Center
    // 3.室藏类统计                        /Room
    // 4.网站、微博、参观展览人次统计        /ThirdPlatform
    // 5.中山档案大数据                    /BigData

    //super.configure(auth);
    //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP2","VIP3","VIP4","VIP5")
            .and()
            .withUser("xwh").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1", "VIP4", "VIP5")
            .and()
            .withUser("wxs").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2", "VIP3");

    //是从数据库中获取认证信息的话,这样写
    //auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
}

}

spring security CSRF防护说明:
CSRF是指跨站请求伪造(Cross-site request forgery),是web常见的攻击之一。
从Spring Security 4.0开始,默认情况下会启用CSRF保护,以防止CSRF攻击应用程序,Spring Security CSRF会针对PATCH,POST,PUT和DELETE方法进行防护。
我这边是spring boot项目,在启用了@EnableWebSecurity注解后,csrf保护就自动生效了。
所以在默认配置下,即便已经登录了,页面中发起PATCH,POST,PUT和DELETE请求依然会被拒绝,并返回403,需要在请求接口的时候加入csrfToken才行。
1.如果你使用了freemarker之类的模板引擎或者jsp,针对表单提交,可以在表单中增加如下隐藏域:

2.如果您使用的是JSON,则无法在HTTP参数中提交CSRF令牌。相反,您可以在HTTP头中提交令牌。一个典型的模式是将CSRF令牌包含在元标记中。下面显示了一个JSP示例:

3.然后,您可以将令牌包含在所有Ajax请求中。如果您使用jQuery,可以使用以下方法完成此操作:
var token = $(“meta[name=’_csrf’]”).attr(“content”);
var header = $(“meta[name=’_csrf_header’]”).attr(“content”);
$.ajax({
url:url,
type:‘POST’,
async:false,
dataType:‘json’, //返回的数据格式:json/xml/html/script/jsonp/text
beforeSend: function(xhr) {
xhr.setRequestHeader(header, token); //发送请求前将csrfToken设置到请求头中
},
success:function(data,textStatus,jqXHR){
}
});

4.如果你不想启用CSRF保护,可以在spring security配置中取消csrf,如下:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()

http.csrf().disable(); //取消csrf防护
}
}
————————————————

你可能感兴趣的:(spring,security)