Delete user

Hi guys im trying to delete a user from the database but i keep getting 403 cant seem to find the problem
@DeleteMapping("/user/{id}")
public ResponseEntity<String> deleteUserById(@PathVariable UUID id) {
userService.deleteUserById(id);
return ResponseEntity.ok("User deleted successfully");
}
@DeleteMapping("/user/{id}")
public ResponseEntity<String> deleteUserById(@PathVariable UUID id) {
userService.deleteUserById(id);
return ResponseEntity.ok("User deleted successfully");
}
public void deleteUserById(UUID id) {
userRepository.deleteById(id);
}
public void deleteUserById(UUID id) {
userRepository.deleteById(id);
}
im getting 403 error in postman deleting a user with the id this is picture of me debugging it Note: I have the user already in my database with the id https://cdn.discordapp.com/attachments/653632542100160547/1221828244882591804/image.png?ex=6613ff3a&is=66018a3a&hm=31741475b0eb312cc675b6459d8bac920bd2fd3628527e3a2d0803432abb650e&
53 Replies
JavaBot
JavaBot11mo ago
This post has been reserved for your question.
Hey @Itsurran! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
tjoener
tjoener11mo ago
403 means you're not authorized or using the wrong url
Itsurran
ItsurranOP11mo ago
I'm authorized doe and have the right url sec gonna try again
Itsurran
ItsurranOP11mo ago
No description
Itsurran
ItsurranOP11mo ago
@RequestMapping("/api/v1/auth") @DeleteMapping("/user/{id}") Should be right url Cant se whats wrong Do you find anything wrong? 2024-03-25T15:55:50.516+01:00 DEBUG 23628 --- [nio-8080-exec-9] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access ??????????????????????? im authorized tho
tjoener
tjoener11mo ago
I'd need to see your code
Itsurran
ItsurranOP11mo ago
This was in my debug console
tjoener
tjoener11mo ago
Ah No you're not 🙂 Bearer tokens expire So might need to get a new one
Itsurran
ItsurranOP11mo ago
Maybe i cant delete a user with the same user? or?
tjoener
tjoener11mo ago
Do you have a spring security config?
Itsurran
ItsurranOP11mo ago
package com.Nem.demo.config;

import jakarta.servlet.Filter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration {

private final JwtAuthenticationFilter jwtAuthFilter;

private final AuthenticationProvider authenticationProvider;

private final LogoutHandler logoutHandler;


@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers("/api/v1/auth/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.logout()
.logoutUrl("/api/v1/auth/logout")
.addLogoutHandler(logoutHandler)
.logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext()
);
return http.build();
}



@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("http://localhost:5173"); // Adjust the origin as needed
config.addAllowedHeader("*");
config.setAllowCredentials(true);
config.addAllowedMethod("*");
source.registerCorsConfiguration("/api/v1/auth/**", config);
return new CorsFilter(source);
}
}
package com.Nem.demo.config;

import jakarta.servlet.Filter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfiguration {

private final JwtAuthenticationFilter jwtAuthFilter;

private final AuthenticationProvider authenticationProvider;

private final LogoutHandler logoutHandler;


@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers("/api/v1/auth/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.logout()
.logoutUrl("/api/v1/auth/logout")
.addLogoutHandler(logoutHandler)
.logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext()
);
return http.build();
}



@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("http://localhost:5173"); // Adjust the origin as needed
config.addAllowedHeader("*");
config.setAllowCredentials(true);
config.addAllowedMethod("*");
source.registerCorsConfiguration("/api/v1/auth/**", config);
return new CorsFilter(source);
}
}
tjoener
tjoener11mo ago
And your user controller?
Itsurran
ItsurranOP11mo ago
I dont have user controller i have authenticationController
package com.Nem.demo.auth;

import com.Nem.demo.user.Role;
import com.Nem.demo.user.User;
import com.Nem.demo.user.UserRepository;
import com.Nem.demo.user.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/auth")
@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:5173", maxAge = 3600, allowCredentials = "true")

public class AuthenticationController {


@Autowired
private final AuthenticationService service;

@Autowired
private final UserRepository userRepository;

@Autowired
private final UserService userService;

@PostMapping("/register")
public ResponseEntity<AuthenticationResponse> register(
@RequestBody RegisterRequest request
) {

if (userRepository.existsByFirstname(request.getFirstname())) {
return ResponseEntity.badRequest().body(new AuthenticationResponse());
}
if (userRepository.existsByEmail(request.getEmail())) {
return ResponseEntity.badRequest().body(new AuthenticationResponse());
}


return ResponseEntity.ok(service.register(request));
}

@PostMapping("/authenticate")
public ResponseEntity<AuthenticationResponse> authenticate(
@RequestBody AuthenticationRequest request
) {
return ResponseEntity.ok(service.authenticate(request));
}
@GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}

@GetMapping("/users/roles")
public List<User> getUsersByRole(@RequestParam("role") Role role) {
return userService.getUsersByRole(role);
}

@GetMapping("user/{id}")
public User findUserByid(@PathVariable UUID id) {
return userService.findUserById(id);
}


@DeleteMapping("/user/{id}")
public ResponseEntity<String> deleteUserById(@PathVariable UUID id) {
userService.deleteUserById(id);
return ResponseEntity.ok("User deleted successfully");
}

}
package com.Nem.demo.auth;

import com.Nem.demo.user.Role;
import com.Nem.demo.user.User;
import com.Nem.demo.user.UserRepository;
import com.Nem.demo.user.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/auth")
@RequiredArgsConstructor
@CrossOrigin(origins = "http://localhost:5173", maxAge = 3600, allowCredentials = "true")

public class AuthenticationController {


@Autowired
private final AuthenticationService service;

@Autowired
private final UserRepository userRepository;

@Autowired
private final UserService userService;

@PostMapping("/register")
public ResponseEntity<AuthenticationResponse> register(
@RequestBody RegisterRequest request
) {

if (userRepository.existsByFirstname(request.getFirstname())) {
return ResponseEntity.badRequest().body(new AuthenticationResponse());
}
if (userRepository.existsByEmail(request.getEmail())) {
return ResponseEntity.badRequest().body(new AuthenticationResponse());
}


return ResponseEntity.ok(service.register(request));
}

@PostMapping("/authenticate")
public ResponseEntity<AuthenticationResponse> authenticate(
@RequestBody AuthenticationRequest request
) {
return ResponseEntity.ok(service.authenticate(request));
}
@GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}

@GetMapping("/users/roles")
public List<User> getUsersByRole(@RequestParam("role") Role role) {
return userService.getUsersByRole(role);
}

@GetMapping("user/{id}")
public User findUserByid(@PathVariable UUID id) {
return userService.findUserById(id);
}


@DeleteMapping("/user/{id}")
public ResponseEntity<String> deleteUserById(@PathVariable UUID id) {
userService.deleteUserById(id);
return ResponseEntity.ok("User deleted successfully");
}

}
here is my userService
package com.Nem.demo.user;


import com.Nem.demo.s3.S3Service;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.UUID;


@Service
@Transactional
public class UserService {

private final UserRepository userRepository;




public UserService(UserRepository userRepository, S3Service s3Service) {this.userRepository = userRepository;

}

public void updateProfileImageUrl(UUID id, String imageUrl) {
User user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("User not found with id: " + id));
user.setImageUrl(imageUrl);
userRepository.save(user);
}



public User findUserById(UUID id) {
return userRepository.findUserById(id);
}


public List<User> getAllUsers() {
return userRepository.findAll();
}


public User getUserByEmail(String email) {
return userRepository.findByEmail(email).orElse(null);
}

public User findImageUrl(UUID id) {
return userRepository.findByImageUrl(String.valueOf(id)).orElse(null);
}


public List<User> getUsersByRole(Role role) {
return userRepository.findByRole(role);
}


public void deleteUserById(UUID id) {
userRepository.deleteById(id);
}
}
package com.Nem.demo.user;


import com.Nem.demo.s3.S3Service;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.UUID;


@Service
@Transactional
public class UserService {

private final UserRepository userRepository;




public UserService(UserRepository userRepository, S3Service s3Service) {this.userRepository = userRepository;

}

public void updateProfileImageUrl(UUID id, String imageUrl) {
User user = userRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("User not found with id: " + id));
user.setImageUrl(imageUrl);
userRepository.save(user);
}



public User findUserById(UUID id) {
return userRepository.findUserById(id);
}


public List<User> getAllUsers() {
return userRepository.findAll();
}


public User getUserByEmail(String email) {
return userRepository.findByEmail(email).orElse(null);
}

public User findImageUrl(UUID id) {
return userRepository.findByImageUrl(String.valueOf(id)).orElse(null);
}


public List<User> getUsersByRole(Role role) {
return userRepository.findByRole(role);
}


public void deleteUserById(UUID id) {
userRepository.deleteById(id);
}
}
wtf can it be
tjoener
tjoener11mo ago
Might be cors stuff
Itsurran
ItsurranOP11mo ago
hm
tjoener
tjoener11mo ago
No idea why you'd put that CrossOrigin header on your controller
Itsurran
ItsurranOP11mo ago
the allowCredentials?
tjoener
tjoener11mo ago
The entire @CrossOrigin
Itsurran
ItsurranOP11mo ago
Because its wining in my frontend
tjoener
tjoener11mo ago
I've never seen or used that
Itsurran
ItsurranOP11mo ago
when i do want to register a user or authneticating should i do a /help
tjoener
tjoener11mo ago
I'm out of ideas tbh But it's usually CORS 😄
Kyo-chan
Kyo-chan11mo ago
I mean it's weird you made a video trying to delete, and you didn't demonstrate that your token system is supposed to work at all, with a GET
Itsurran
ItsurranOP11mo ago
What do you mean? he token system works since the other endpoint that require authentication gets a response I just copied the token that i got from the authentication to use in my bearer
Kyo-chan
Kyo-chan11mo ago
You didn't show that
Itsurran
ItsurranOP11mo ago
Ok sec lemme show better
Itsurran
ItsurranOP11mo ago
buts its step for step i register first then i authenticate i get the token from the database and then try to delete
Kyo-chan
Kyo-chan11mo ago
.... Try to get rather than delete
Itsurran
ItsurranOP11mo ago
wrosk works
Itsurran
ItsurranOP11mo ago
No description
Kyo-chan
Kyo-chan11mo ago
Then it can't hurt to make a summary, that mentions that GET works and not DELETE, and yes invite other people to try and help, in case they've seen weird things and have good ideas
Itsurran
ItsurranOP11mo ago
What do you mean exatcly? of ur last senteces
Kyo-chan
Kyo-chan11mo ago
I mean that you should describe clearly your situation, such as you know the GET works, it's the DELETE, same URI same authentication, that doesn't and gives a 403 instead
Itsurran
ItsurranOP11mo ago
True but i never tried to get since u mentioned it.
Kyo-chan
Kyo-chan11mo ago
Beside that, sure, you have a right to hope for help from other people who may have good ideas
Itsurran
ItsurranOP11mo ago
Should i try to ping?
Kyo-chan
Kyo-chan11mo ago
Does it sound helpful?
Itsurran
ItsurranOP11mo ago
If you or tjoener are out of ideas i think then yes.
Kyo-chan
Kyo-chan11mo ago
Write a summary, and mention that help is still needed Unread channels are written in bright white. People can't miss that someone needs help, they can only choose to ignore so
Itsurran
ItsurranOP11mo ago
Thanks for the heads up
JavaBot
JavaBot11mo ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
dan1st
dan1st11mo ago
Can you try using verbose logging for Spring security? and for the same endpoint, you are getting a 403 on DELETE but not on GET even though CSRF is disabled?
Itsurran
ItsurranOP11mo ago
Yes, true. Ok sec Ohh i know the problem update or delete on table "users" violates foreign key condition "fkj8rfw4x0wjjyibfqq566j4qng" for table "token" Cant delete a user when it has a token for some reason
dan1st
dan1st11mo ago
yes but you can configure to delete the token with it
Itsurran
ItsurranOP11mo ago
ahhhhhhh fk me true
dan1st
dan1st11mo ago
(cascading)
Itsurran
ItsurranOP11mo ago
So like ON DELETE CASCADE?
dan1st
dan1st11mo ago
yes try that
Itsurran
ItsurranOP11mo ago
yes sec Working now! thanks @dan1st | Daniel ❤️
JavaBot
JavaBot11mo ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
JavaBot
JavaBot11mo ago
Post Closed
This post has been closed by <@265561438452580353>.

Did you find this page helpful?