До того, как я ограничил запросы PUT, POST и DELETE для определенных ролей, все работало нормально.Но теперь при каждом запросе, кроме GET, я получаю this .
Я не уверен, но я думаю, что что-то не так с HiddenHttpMethodFilter и Spring Security не может распознать PUT и DELETE запросы, но в этом случаепочему POST также не поддерживается ...
Я пытался отключить csrf, но он не дал результата.
SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final DataSource dataSource;
@Autowired
public SecurityConfig(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(POST).hasRole("ADMIN")
.antMatchers(DELETE).hasRole("ADMIN")
.antMatchers(PUT).hasAnyRole( "ADMIN","MANAGER")
.antMatchers("/employees/**").hasRole("EMPLOYEE")
.antMatchers("/css/**").permitAll()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/authenticateUser")
.permitAll()
.and()
.logout().permitAll()
.and()
.exceptionHandling().accessDeniedPage("/access-denied");
}
@Bean
public UserDetailsManager userDetailsManager() {
JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager();
jdbcUserDetailsManager.setDataSource(dataSource);
return jdbcUserDetailsManager;
}
}
DispatcherServletInitializer.java
public class DispatcherServletInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) {
AnnotationConfigWebApplicationContext context
= new AnnotationConfigWebApplicationContext();
context.setConfigLocation("com.tracker.config");
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext
.addServlet("dispatcher", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
registerHiddenFieldFilter(servletContext);
}
private void registerHiddenFieldFilter(ServletContext context) {
context.addFilter("hiddenHttpMethodFilter", new HiddenHttpMethodFilter()).addMappingForUrlPatterns(null, true, "/*");
}
}
EmployeeControler.java
@Controller
@RequestMapping("/employees")
public class EmployeeController {
//get mappings ommited
@PostMapping({"", "/"})
public String save(@Valid @ModelAttribute("employee") Employee employee,
BindingResult bindingResult) {
if (bindingResult.hasErrors())
return "new";
employeeService.saveEmployee(employee);
return "redirect:/employees/";
}
@PutMapping(value = "/{id}")
public String update(@Valid @ModelAttribute("employee") Employee employee,
BindingResult bindingResult) {
if (bindingResult.hasErrors())
return "edit";
employeeService.saveEmployee(employee);
return "redirect:/employees/";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable(value = "id") int id) {
employeeService.deleteEmployee(id);
return "redirect:/employees/";
}
И new.jsp в качестве примера формы сообщения
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<html>
<head>
<title>List Employees</title>
<link type="text/css"
rel="stylesheet"
href="${pageContext.request.contextPath}/css/style.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"/>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">Employee Tracker</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<form:form class="form-inline my-2 my-lg-0" action="${pageContext.request.contextPath}/logout" method="POST">
<input class="btn btn-lg" type="submit" value="logout"/>
</form:form>
</div>
</nav>
<div class="container">
<h1>EMPLOYEES TRACKER</h1>
<form:form class="input-form" action="/employees" modelAttribute="employee" method="post">
<div class="form-group justify-content-center row">
<label for="first_name" class="col-sm-2 col-form-label">First Name</label>
<div class="col-sm-10">
<form:input path="firstName" type="text" class="form-control" id="first_name"/>
<form:errors path="firstName" cssClass="error" />
</div>
</div>
<div class="form-group row">
<label for="last_name" class="col-sm-2 col-form-label">Last Name</label>
<div class="col-sm-10">
<form:input path="lastName" type="text" class="form-control" id="last_name"/>
<form:errors path="lastName" cssClass="error" />
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<form:input path="email" type="text" class="form-control" id="email"/>
<form:errors path="email" cssClass="error" />
</div>
</div>
<div class="form-group row">
<label for="phone_number" class="col-sm-2 col-form-label">Phone Number</label>
<div class="col-sm-10">
<form:input path="phoneNumber" type="text" class="form-control" id="phone_number"/>
<form:errors path="phoneNumber" cssClass="error" />
</div>
</div>
<div class="form-group row">
<label for="photo" class="col-sm-2 col-form-label">Photo URL</label>
<div class="col-sm-10">
<form:input path="photo" type="text" class="form-control" id="photo"/>
</div>
</div>
<form:button type="submit" class="btn btn-primary btn-lg btn-block">Save</form:button>
</form:form>
<a class="btn" href="${pageContext.request.contextPath}/employees/">Back to list</a>
</div>
<div id="footer" class="card-footer text-muted">
Ⓒ Employees Tracker
</div>
</body>
</html>