Reputation: 11
For below code getEmployees
Working fine with user name : "user" and password as generated by spring. But when I tried to POST/PUT an employee. I am getting 403 though same authorization working for GET.
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();
}
}
Upvotes: 0
Views: 290
Reputation: 11
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();
}
}
Upvotes: 1
Reputation: 15908
If you're using Spring 4+, you need to deal with CSRF protection. This passes a token around to make sure that it's really the Javascript on your site that's doing the call.
You can either turn it off with a simple config entry, or you have to add a few small things to your app; both to your page and the javascript.
You can disable the csrf like below.
@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);
}
Upvotes: 0