Я сталкиваюсь с ошибкой 403 - Access denied
каждый раз, когда пытаюсь нажать этот безопасный метод. Я могу поразить все другие методы, кроме этого безопасного. Если это имеет значение, я использую H2 DB.
Я впервые пытаюсь spring security
. Так что прости меня за любые простые ошибки
@RestController
public class ProductController {
@Autowired
private ProductService productService;
@PreAuthorize("hasRole('ADMIN')")
@PostMapping("/addProduct")
public ResponseEntity<String> addProduct(@RequestBody Product product) {
if (productService.addProduct(product)) {
return new ResponseEntity<String>("newly added " + product.getName(), HttpStatus.CREATED);
}
return new ResponseEntity<String>("Could not add product " + product.getName(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Мой класс конфигурации Spring выглядит следующим образом:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String authoritiesQuery = "SELECT USERNAME, ROLE FROM TBLUSERS WHERE USERNAME = ?";
private static final String usersQuery = "SELECT USERNAME, PASSWORD, 1 as enabled FROM TBLUSERS WHERE USERNAME = ?";
@Autowired
private DataSource dataSource;
@Autowired
protected void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).authoritiesByUsernameQuery(authoritiesQuery)
.usersByUsernameQuery(usersQuery).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers(HttpMethod.POST, "/addProduct").hasRole("ADMIN").antMatchers("/").permitAll().and().authorizeRequests()
.antMatchers("/console/**").permitAll();
httpSecurity.csrf().disable();
httpSecurity.headers().frameOptions().disable();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(10);
}
}
Мои записи H2 DB:
MERGE INTO TBLUSERS VALUES ('Abhi', '$2a$10$5uSoNE.xI.0Pe4uoy1Pd/ushJPh0O32Sa6W/CybjBp9FrytEuPGvq', 'ROLE_USER');
MERGE INTO TBLUSERS VALUES ('Abhishek', '$2a$10$5uSoNE.xI.0Pe4uoy1Pd/ushJPh0O32Sa6W/CybjBp9FrytEuPGvq', 'ROLE_ADMIN');
MERGE INTO TBLUSERS VALUES ('Abhishek', '$2a$10$5uSoNE.xI.0Pe4uoy1Pd/ushJPh0O32Sa6W/CybjBp9FrytEuPGvq', 'ROLE_USER');