不允许使用HTTP 405-Spring Boot + Spring Security [英] HTTP 405 Not Allowed - Spring Boot + Spring Security

查看:446
本文介绍了不允许使用HTTP 405-Spring Boot + Spring Security的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的rest API,可与数据库一起使用.在添加安全性部分之前,它一直工作正常.现在,它在POST和DELETE请求上提供HTTP 405不允许.我不知道为什么. GET请求正常工作.

I have a simple rest API which works with database. It worked properly until I added the security part. Now it gives HTTP 405 Not Allowed on the POST and DELETE requests. I have no idea why. The GET requests work properly.

这是控制器类:

@Controller
public class MarkerController {

    private Logger logger = Logger.getLogger(MarkerController.class.getName());

    @Autowired
    private MarkerServiceInterface markerService;

    @RequestMapping(value="/markers", method=RequestMethod.GET)
    public @ResponseBody List<Marker> getMarkers(@RequestParam(value="city", defaultValue="") String city) {
        logger.info("HANDLE GET REQUEST");



        return this.markerService.getAllMarkers();
    }

    @RequestMapping(value="/markers/new", method=RequestMethod.POST)
    public @ResponseBody Marker addMarker(@RequestBody Marker marker) {
        logger.info("HANDLE POST REQUEST");

        this.markerService.addMarker(marker);
        return marker;
    }

    @RequestMapping(value="/markers/delete", method=RequestMethod.DELETE)
    public @ResponseBody String deleteMarker(@RequestParam(value="id", defaultValue="") String id) {
        logger.info("HANDLE DELETE REQUEST");
        if (!id.equals("")) {
            logger.info(id);
            this.markerService.deleteMarker(Long.parseLong(id));
        }
        return "";
    }

    @RequestMapping(value="/admin/map")
    public String trafficSpy() {
        logger.info("HANDLE MAP");
        return "index";
    }

    @RequestMapping(value="/admin")
    public String admin() {
        return "admin";
    }

    @RequestMapping(value="/login")
    public String login() {
        return "login";
    }

}

这是SecurityConfig:

This is the SecurityConfig:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(
                passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http    
            .authorizeRequests()
            .antMatchers("/admin/**")
            .access("hasRole('ROLE_ADMIN')")
            .antMatchers("/markers/**")
            .access("hasRole('ROLE_USER')")
            .and()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .usernameParameter("username")
            .passwordParameter("password")
            .and()
            .logout()
            .logoutSuccessUrl("/login?logout")
            .and()
            .csrf()
            .and()
            .exceptionHandling()
            .accessDeniedPage("/403");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Bean
    public DaoAuthenticationProvider authProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }
}

使用以下ajax代码调用DELETE请求:

The DELETE request is called with the following ajax code:

$.ajax({
        url: "localhost:8080/markers/delete?id=" + currentMarker.get("id"),
        type: 'DELETE',
        success: function(result) {
            console.log(result);
        }
    });

这是控制台中给出的消息:

And here is the message given in the console:

2015-05-11 15:48:13.671  WARN 8279 --- [nio-8181-exec-6] o.s.web.servlet.PageNotFound             : Request method 'DELETE' not supported

这些是响应的标题.我可以看到,在AlLLOW中,我只有GET和HEAD.因此,如果我是对的,则意味着控制器中的方法仅接受GET和HEAD请求.

These are the headers of the response. I can see that in AlLLOW I have only GET and HEAD. So if I'm right, this means that the method in the controller accepts only GET and HEAD requests.

(Status-Line)               HTTP/1.1 405 Method Not Allowed
Server                      Apache-Coyote/1.1
x-content-type-options      nosniff
x-xss-protection            1; mode=block
Cache-Control               no-cache, no-store, max-age=0, must-revalidate
Pragma                      no-cache
Expires                     0
X-Frame-Options             DENY
Allow                       GET, HEAD
Content-Type                application/json;charset=UTF-8
Transfer-Encoding           chunked
Date                        Mon, 11 May 2015 17:35:31 GMT

在回复中,我有以下例子:

In the response I have this exeption:

org.springframework.web.HttpRequestMethodNotSupportedException

任何想法导致此问题的原因是什么?如何允许POST和DELETE方法?

Any idea what is causing this problem? How can I allow the POST and DELETE methods?

推荐答案

您忘记了csrf-令牌.

建议您在meta-tag中添加csrf-Token.您可以在

It's recommended that you add the csrf-Token in the meta-tag. You can read it in the Spring Security Documentation

您可以执行以下操作:

$(function () {
  var token = $("meta[name='_csrf']").attr("content");
  var header = $("meta[name='_csrf_header']").attr("content");
  $(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(header, token);
  });
});

这篇关于不允许使用HTTP 405-Spring Boot + Spring Security的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆