Как сделать так чтобы только создатель мог удалять свою запись Spring Security
Допустим пользователь сосздал свой коментарий. Как сделать так чтобы только он мог его удалить а не кто-то другой кто знает Id коменатрия?
@DeleteMapping("/updateComment/{commentId}")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> deleteComment(@PathVariable("commentId") Comment comment){
return commentService.deleteComment(comment);
}
Мой Spring Security
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
prePostEnabled = true
)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private UserDetailsServiceImpl userDetailsService;
private AuthEntryPointJwt unauthorizedHandler;
@Autowired
public WebSecurityConfig(UserDetailsServiceImpl userDetailsService, AuthEntryPointJwt unauthorizedHandler){
this.userDetailsService = userDetailsService;
this.unauthorizedHandler = unauthorizedHandler;
}
@Bean
public AuthTokenFilter authenticationJwtTokenFilter(){
return new AuthTokenFilter();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests().antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/profile/**").permitAll()
.antMatchers("/api/posts/**").permitAll()
.antMatchers("/api/tags/**").permitAll()
.antMatchers("/api/images/**").permitAll()
.antMatchers("/images/**").permitAll()
.antMatchers("/avatars_min/**").permitAll()
.antMatchers("/avatars_full/**").permitAll()
.antMatchers("/posts_images/**").permitAll()
.antMatchers("/topic/**").permitAll()
.antMatchers("/socket/**").permitAll()
.antMatchers("/notify/**").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
Ответы (1 шт):
Автор решения: ЮрийСПб
→ Ссылка
Добавьте проверку юзера перед удалением. Например как-то так:
@DeleteMapping("/updateComment/{commentId}")
@PreAuthorize("hasRole('USER')")
public ResponseEntity<?> deleteComment(
@PathVariable("commentId") Comment comment,
@AuthenticationPrincipal User user
) {
if (comment.getAuthorId() == user.getId()) {
return commentService.deleteComment(comment);
} else {
throw new RuntimeException("Access denied!");
}
}