Always @GetMapping Enpoints 与 BasicAuthentication Credentials 一起工作正常,但是用于注册新用户的 @PostMapping 端点总是给出“401”,即使我注释掉了所有 Spring Security 配置文件....
这是我的 Repo 和控制器
用户回购
package com.example.ecommerce_backend.Repository;
import com.example.ecommerce_backend.Model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface UserRepo extends JpaRepository<User,Integer> {
@Query(value = "SELECT * from user", nativeQuery = true)
List<Object[]> findColumnsOnly();//Retrieving data as Object[] instances with this it is possible to retrieve only specific columns
Optional<User> findByEmail(String email);
User save(User user);
}
控制器
package com.example.ecommerce_backend.Controller;
import com.example.ecommerce_backend.Model.User;
import com.example.ecommerce_backend.Repository.UserRepo;
import com.example.ecommerce_backend.Service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
private UserService userService;
private UserRepo userRepo;
public UserController(UserService userService, UserRepo userRepo) {
this.userService = userService;
this.userRepo = userRepo;
}
@GetMapping
public String Hello(){
return "Hello Brother";
}
// @PreAuthorize("hasRole('Admin')")//Allowing that which user have Granted to access this method at Method Level
@GetMapping("/allUsers")
public List<Object[]> getAllUsers(){
return userService.getAllUsers();
}
@GetMapping("/customerMessage")
public String show(){
return "Hello Customer";
}
@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody User user) {
if(userRepo.findByEmail(user.getEmail()).isPresent()){
return ResponseEntity.badRequest().body("This email already exists");
}
else {
String encodedPassword = new BCryptPasswordEncoder().encode(user.getPassword());
user.setPassword(encodedPassword);
// user.setRole("ROLE_CUSTOMER");
userRepo.save(user);
return ResponseEntity.ok("User registered successfully");
}
}
}
我需要知道为什么会这样,这是什么原因,有人可以帮我解决这个问题吗???