【发布时间】:2020-05-15 04:50:37
【问题描述】:
您能否向我解释一下如何在邮递员中发出 POST 请求以将新用户添加到我的用户集合中。
问题是我可以使用 Get Request 添加用户,但 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);
}
为了在我的数据库中添加一个用户,我在邮递员的正文中添加了这段代码:
{
"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 中添加了 Spring Security 依赖。如果是这样,请检查控制台中打印的日志以生成随机密码。使用生成的密码和用户名
user。 -
@Mansoor 是的,我使用 Spring Security,我有这种依赖关系。在 Postman 中,我在“授权”类型“基本身份验证”部分添加了 Spring Security“使用”的默认用户名和我的应用程序服务器生成的密码
-
你能添加你的控制器方法吗?
标签: spring mongodb post spring-data postman