小编典典

spring安全403错误

spring-mvc

我正在尝试按照网络上的指南使用Spring安全性来保护我的网站。所以在我的服务器端,WebSecurityConfigurerAdapter和控制器看起来像这样

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter
implements ApplicationContextAware {

@Override
protected void registerAuthentication(AuthenticationManagerBuilde r authManagerBuilder) throws Exception {
authManagerBuilder.inMemoryAuthentication()
.withUser("user").password("password").roles("ADMI N");
}
}

@Controller
//@RequestMapping("/course")
public class CourseController implements ApplicationContextAware{

@RequestMapping(value="/course", method = RequestMethod.GET, produces="application/json")
public @ResponseBody List<Course> get(// The critirion used to find.
@RequestParam(value="what", required=true) String what,
@RequestParam(value="value", required=true) String value) {
//.....
}

@RequestMapping(value="/course", method = RequestMethod.POST, produces="application/json")
public List<Course> upload(@RequestBody Course[] cs) {
}
}

让我非常困惑的是,服务器不响应POST / DELETE方法,而GET方法可以正常工作。顺便说一句,我在客户端上使用RestTemplate。例外情况是:

Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 403 Forbidden
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:574)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:530)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:487)
    at org.springframework.web.client.RestTemplate.delete(RestTemplate.java:385)
    at hello.Application.createRestTemplate(Application.java:149)
    at hello.Application.main(Application.java:99)

我已经在互联网上搜索了几天。还是没有头绪。请帮忙。非常感谢


阅读 1923

收藏
2020-06-01

共1个答案

小编典典

该问题可能是由于CSRF保护所致。如果用户不会在Web浏览器中使用您的应用程序,则可以安全地禁用CSRF保护。否则,您应确保在请求中包含CSRF令牌

禁用CSRF保护,可以使用以下命令:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig
    extends WebSecurityConfigurerAdapter implements ApplicationContextAware {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // ...
            .csrf().disable();
    }

    @Override
    protected void registerAuthentication(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("ADMIN");
    }
}
2020-06-01