serverhttpsecurity 缺少,不允许使用HTTP 405-Spring Boot + Spring Security

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.

So here is the controller class:

@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 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";

}

}

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;

}

}

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

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

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

解决方案

You forget the csrf-Token.

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

With this you can do the following:

$(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);

});

});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 是一个用于构建微服务的开源框架,它能够快速搭建项目并且提供了许多便捷的功能和特性。Spring Security 是一个用于处理认证和授权的框架,可以保护我们的应用程序免受恶意攻击。JWT(JSON Web Token)是一种用于身份验证的开放标准,可以被用于安全地传输信息。Spring MVC 是一个用于构建 Web 应用程序的框架,它能够处理 HTTP 请求和响应。MyBatis 是一个用于操作数据库的框架,可以简化数据库操作和提高效率。Redis 是一种高性能的键值存储系统,可以用于缓存与数据存储。 基于这些技术,可以搭建一个商城项目。Spring Boot 可以用于构建商城项目的后端服务,Spring Security 可以确保用户信息的安全性,JWT 可以用于用户的身份验证,Spring MVC 可以处理前端请求,MyBatis 可以操作数据库,Redis 可以用于缓存用户信息和商品信息。 商城项目的后端可以使用 Spring BootSpring Security 来搭建,通过 JWT 来处理用户的身份验证和授权。数据库操作可以使用 MyBatis 来简化与提高效率,同时可以利用 Redis 来缓存一些常用的数据和信息,提升系统的性能。前端请求则可以通过 Spring MVC 来处理,实现商城项目的整体功能。 综上所述,借助于 Spring BootSpring Security、JWT、Spring MVC、MyBatis 和 Redis 这些技术,可以构建出一个高性能、安全可靠的商城项目,为用户提供良好的购物体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值