403 Запрещенный запрос на отправку весенней загрузки не работает - PullRequest
0 голосов
/ 27 мая 2020

У меня есть 403 запрещенный запрос при запросе POST с помощью почтальона, get работает отлично, и я не использую какие-либо инструменты безопасности Spring, просто весеннюю загрузку, потому что я видел некоторые ответы, в которых говорится об отключении csrf, что не в моем случае, потому что я без использования пружинной безопасности.

Вот мой класс Entity:

   package com.example.demo.entity;

   import java.util.Date;
   import javax.persistence.Column;
   import javax.persistence.Entity;
   import javax.persistence.Id;
   import javax.persistence.PrePersist;
   import javax.persistence.Table;
   import javax.validation.constraints.NotBlank;
   import javax.validation.constraints.Size;


   @Entity
   @Table(name="clients")
   public class Clients {

    @Id
    @Column(name="phone")
    private Long phone;

    @NotBlank(message="Required Field")
    @Column(name="firstname")
    private String firstname;

    @NotBlank(message="Required Field") 
    @Column(name="lastname")
    private String lastname;

    @NotBlank(message="Required Field") 
    @Column(name="birthDate")
    private String birthDate;

    @NotBlank(message="Required Field") 
    @Column(name="email")
    private String email;

    @NotBlank(message="Required Field") 
    @Column(name="addressClient")
    private String addressClient;

    @NotBlank(message="Required Field") 
    @Column(name="gender")
    private String gender;


    @Column(name="inscriptionDate")
    private Date inscriptionDate;

    @NotBlank(message="Required Field") 
    @Size(min=8 , message="Password needs to be more than 8 characters")
    @Column(name="passwordClient")
    private String passwordClient;


    public Clients() {

    }



    public Clients(Long phone, @NotBlank(message = "Required Field") String firstname,
            @NotBlank(message = "Required Field") String lastname,
            @NotBlank(message = "Required Field") String birthDate, @NotBlank(message = "Required Field") String email,
            @NotBlank(message = "Required Field") String addressClient,
            @NotBlank(message = "Required Field") String gender, Date inscriptionDate,
            @NotBlank(message = "Required Field") @Size(min = 8, message = "Password needs to be more than 8 characters") String passwordClient) {
        super();
        this.phone = phone;
        this.firstname = firstname;
        this.lastname = lastname;
        this.birthDate = birthDate;
        this.email = email;
        this.addressClient = addressClient;
        this.gender = gender;
        this.inscriptionDate = inscriptionDate;
        this.passwordClient = passwordClient;
    }



    @PrePersist
    public void newDate() {
        this.inscriptionDate=new Date();
    }

    public Long getPhone() {
        return phone;
    }

    public void setPhone(Long phone) {
        this.phone = phone;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(String birthDate) {
        this.birthDate = birthDate;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAddressClient() {
        return addressClient;
    }

    public void setAddressClient(String addressClient) {
        this.addressClient = addressClient;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getInscriptionDate() {
        return inscriptionDate;
    }

    public void setInscriptionDate(Date inscriptionDate) {
        this.inscriptionDate = inscriptionDate;
    }

    public String getPasswordClient() {
        return passwordClient;
    }

    public void setPasswordClient(String passwordClient) {
        this.passwordClient = passwordClient;
    }
    }

И вот мой интерфейс репозитория:

    package com.example.demo.repositories;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.jpa.repository.JpaRepository;
    import org.springframework.stereotype.Repository;

    import com.example.demo.entity.Clients;

    @Repository
    public interface ClientsRepository extends JpaRepository<Clients , Long>{
    } 

Мой класс контроллера:

     package com.example.demo.controllers;

     import java.util.ArrayList;
     import java.util.List;
     import java.util.Optional;

     import javax.validation.Valid;

     import org.springframework.beans.factory.annotation.Autowired;
     import org.springframework.http.HttpStatus;
     import org.springframework.http.ResponseEntity;
     import org.springframework.web.bind.annotation.CrossOrigin;
     import org.springframework.web.bind.annotation.DeleteMapping;
     import org.springframework.web.bind.annotation.GetMapping;
     import org.springframework.web.bind.annotation.PathVariable;
     import org.springframework.web.bind.annotation.PostMapping;
     import org.springframework.web.bind.annotation.PutMapping;
     import org.springframework.web.bind.annotation.RequestBody;
     import org.springframework.web.bind.annotation.RequestParam;
     import org.springframework.web.bind.annotation.RestController;

     import com.example.demo.entity.Clients;
     import com.example.demo.functions.ClientsFunctionsImpl;
     import com.example.demo.repositories.ClientsRepository;



   @RestController
   public class ClientsController {

   @Autowired
   private ClientsRepository clientsRepository;


   @CrossOrigin("http://localhost:3000")
   @GetMapping(path="/clientslist")
   public List<Clients> getAllClients(){

     return clientsfunctionsimpl.list();

   }



   @CrossOrigin("http://localhost:3000")
   @PostMapping("/clientslist")
   public ResponseEntity<Clients> createEmployee(@Valid @RequestBody Clients client) {

    Clients client1 = clientsRepository.save(client);

    return new ResponseEntity<Clients>(client1,HttpStatus.CREATED);
   }
   }

Ответы [ 2 ]

0 голосов
/ 27 мая 2020

Ваш код работает, но я хочу добавить еще одну вещь: использование этого типа структуры предотвратит внедрение SQL и улучшит ваш ответ API создания.

        @CrossOrigin(origins = "http://localhost:3000")
        @PostMapping(value = "/createEmployee")
        public ResponseEntity<ClientsMetaModel> createEmployee(@Valid @RequestBody ClintsModel model) {
            ClientsMetaModel metaModel = new ClientsMetaModel();
            // set all your fields into metamodel by getting it from model
            return new ResponseEntity<ClientsMetaModel>(empRepo.save(metaModel), HttpStatus.CREATED);
        }

Вы должны сохранить свой id, token, date все поля в только метамодель и попробуйте это.
Если это не сработает, используйте @CrossOrigin(/*) как глобальный. Также, как сказал @Ananthapadmanabhan в своем ответе, но я советую вам использовать концепцию модели и метамодели.

0 голосов
/ 27 мая 2020

Не могли бы вы попробовать включить CORS для всех портов и URL-адресов вашей конечной точки, например:

  @CrossOrigin
   @PostMapping("/clientslist")
   public ResponseEntity<Clients> createEmployee(@Valid @RequestBody Clients client) {

    Clients client1 = clientsRepository.save(client);

    return new ResponseEntity<Clients>(client1,HttpStatus.CREATED);
   }
...