簡體   English   中英

Juste GET 請求與 POSTMAN 一起工作,POST 請求返回 403Forbidden:Spring Boot mongoDB(郵遞員測試)

[英]Juste GET Request work with POSTMAN, POST Request return 403Forbidden : Spring Boot mongoDB (Postman Test)

您能否向我解釋如何在郵遞員中發出 POST 請求以將新用戶添加到我的用戶集合中。

問題是我可以使用 Get 請求添加用戶,但 POST 請求返回 403 Forbidden。

你能告訴我如何授權 POST 請求嗎?

我在我的控制器中嘗試了這個解決方案,但沒有什么是固定的:

@RequestMapping(value = "/users", method = { RequestMethod.GET, RequestMethod.DELETE, RequestMethod.POST })

在 spring-boot 中,我有 3 個實體:用戶、中心和角色

它們與以下各項之間的關系:

類用戶:

@Document
public class User {

    @Id
    private String id;
    private String login;
    private String password;
    private String nom;
    private String prenom;
    private long telephone;
    private long idCCMS;
    private String matricule;

    @DBRef
    private Centre centres;

    @DBRef
    private Role roles;

班級角色:

@Document
public class Role {

    @Id
    private String id;
    private String role;
    private String description;

    @DBRef
    private Collection<User> users = new ArrayList<>();

班級中心

@Document
public class Centre {

    @Id
    private String id;
    private String reference;
    private String libelle;

    @DBRef
    private Collection<User> users = new ArrayList<>();

我的存儲庫:

@Repository
public interface UserRepository extends MongoRepository<User, String> {

    List<User>findByMatricule(String matricule);
    User findByLogin(String login);
    List<User>findByNom(String nom);
    List<User>findByPrenom(String prenom);
}

我的控制器:

@RestController
@RequestMapping(value = "/users", method = { RequestMethod.GET, RequestMethod.DELETE, RequestMethod.POST })
@CrossOrigin(origins = { "http://localhost:4200" })
public class UserController {

    @Autowired
    private UserRepository userRepo;

//  @Autowired
//  private MongoTemplate mtUser;

    @GetMapping("/all")
    @Query(value = "{}", fields = "{'objectContentAsJson':0}")
    public Iterable<User> getall() {
        return (userRepo.findAll());
    }

    @PostMapping("/add")
    public User save(@RequestBody User user) {
        return userRepo.save(user);
    }

為了在我的數據庫中添加一個用戶,我在 postman 的正文中添加了以下代碼:

{
    "id": "5e319750fcf3c73b589b6211",
    "login": "aaaa",
    "password": "aaaa",
    "nom": "aaaa",
    "prenom": "aaaa",
    "telephone": 97408105,
    "idCCMS": 123456,
    "matricule": "mat123",
    "centres": "5e319dd0730b1659d5910e0c",
    "roles": "5e319dd0730b1659d5910e0d"
}

在json代碼的center和role字段中添加Center ID和Role ID是否正確?

在此處輸入圖片說明

在 Postman 中,我在“授權”類型“基本身份驗證”部分中添加了 Spring Security“使用”的默認用戶名和我的應用程序服務器生成的密碼:

在此處輸入圖片說明 在此處輸入圖片說明 在此處輸入圖片說明

響應是401 Unauthorized ,這意味着您需要在請求中添加用戶名和密碼。

在你的 pom.xml 中查看你是否有依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

如果以上為真,Spring security 將生成一個隨機密碼。 使用它與用戶名一起作為user在 Postman 中進行身份驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM