POST请求的Spring安全配置

时间:2016-12-29 05:25:26

标签: spring-mvc spring-security

我在Rest API中配置了spring security。我有三种控制器方法。一个使用GET,另外两个使用POST。 现在,我使用了基本身份验证。 问题是安全性对GET请求正常,但对POST请求没有。

  

使用POST方法时,我总是收到403 Forbidden响应请求。

控制器类:

package com.base.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.base.model.User;
import com.base.service.UserService;

@RestController

public class CountryController {




  @Autowired
  UserService userService;  //Service which will do all data retrieval/manipulation work


    //-------------------Retrieve All Users--------------------------------------------------------

    @RequestMapping(value = "/user/", method = RequestMethod.POST)
    public ResponseEntity<List<User>> listAllUsers() {
        List<User> users = userService.findAllUsers();
        if(users.isEmpty()){
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }


    //-------------------Retrieve Single User--------------------------------------------------------

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    public ResponseEntity<User> getUser(@PathVariable("id") long id) {
        System.out.println("Fetching User with id " + id);
        User user = userService.findById(id);
        if (user == null) {
            System.out.println("User with id " + id + " not found");
            return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<User>(user, HttpStatus.OK);
    }

    @RequestMapping(value = "/user123", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.ALREADY_REPORTED)
    public User postUser(@RequestBody @Valid User user) {
        System.out.println("Fetching User with id " + user.getId());
        user.setName("Tou added");
        return user;
    }
}

安全配置:

@Configuration
@EnableWebSecurity
@ComponentScan("com.base.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
MyUSerService userService;

@Autowired
public void configureGlobalAuth(final AuthenticationManagerBuilder auth)throws Exception{
    auth.userDetailsService(userService);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    // TODO Auto-generated method stub
    http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}

MyUserService(提供用户名和密码)

 @Service
public class MyUSerService implements UserDetailsService{



    @Override
    public UserDetails loadUserByUsername(String arg0) throws UsernameNotFoundException {
        // TODO Auto-generated method stub
        List<SimpleGrantedAuthority> authoriities = new ArrayList<SimpleGrantedAuthority>();
        authoriities.add(new SimpleGrantedAuthority("WRITE"));
        return new User("ayush","ayush123",authoriities);
    }
    }

Web.xml中

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <display-name>Archetype Created Web Application</display-name>



    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>springrest</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextClass</param-name>
            <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext
            </param-value>
        </init-param>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>com.base.config</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springrest</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>  

我正在使用Google Advanced Rest Client&#39;。

2 个答案:

答案 0 :(得分:5)

您需要禁用CRSF。春季安全中的CRSF is enabled by default 4。

http.csrf().disable()

或发送请求with CRSF token

答案 1 :(得分:1)

在Spring Security 4.0中,默认情况下使用XML配置启用CSRF保护。您必须禁用CSRF保护,相应的XML。

<http>
    <!-- ... -->
    <csrf disabled="true"/>
</http>

或者您可以通过以下

在代码库中禁用Java configration文件
http.csrf().disable();