启用S​​pring Boot默认安全性:Rest Service GET正常运行,PUT和POST失败并显示403错误

时间:2018-07-16 18:05:22

标签: spring spring-boot spring-security

对于下面的代码getEmployees,可以正常使用用户名:“ user”和spring生成的密码。但是,当我尝试POST / PUT一名员工时。尽管获得GET的相同授权,但我却收到403。

package com.spring.boot.employee;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RestController;

import com.spring.boot.employee.domain.Employee;
import com.spring.boot.employee.service.EmployeeService;

@RestController
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    @RequestMapping(value = "addEmployee", method = RequestMethod.PUT, consumes = { "application/json",
            "application/xml" }, produces = { "application/json" })
    public ResponseEntity<String> insertEmployee(@RequestBody Employee employee) {
        try {
            employeeService.insertEmployee(employee);
            return ResponseEntity.status(HttpStatus.CREATED).body("Empolyee inserted Suceessfully");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Empolyee inserted failed");
        }

    }

    @RequestMapping(value = "getAllEmployees", method = RequestMethod.GET , produces = { "application/json" })
    public List<Employee> getAllEmployee() {
        return employeeService.getAllEmployees();
    }                 
}

2 个答案:

答案 0 :(得分:0)

如果您使用的是Spring 4+,则需要处理CSRF保护。这样会传递一个令牌,以确保调用时确实是您网站上的Javascript。

您可以通过一个简单的配置条目将其关闭,或者必须在应用程序中添加一些小东西。到您的页面和javascript。

您可以像下面那样禁用csrf。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().authorizeRequests().anyRequest().
    authenticated().and().formLogin().loginPage("/login").
    permitAll().and().logout().deleteCookies("rememberme").
    permitAll().and().rememberMe().tokenValiditySeconds(60);
}

答案 1 :(得分:0)

Adding below security config class will resolve the issue.

package com.spring.boot.employee;

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;

@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {

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