-1

So here is the thing. I have 2 tables in the database: User and Client.

A user can add one or many clients in the database. So what I want is when a user will add a client - the function will retrieve the id of the logged in User and add it as a foreign key in the client table.

I have already done the OneToMany Mapping.

Here is my controller:

@RequestMapping(value = "/postficheclient", method = RequestMethod.POST)
public ResponseEntity<?> createClient(@RequestBody Client newClient) {
    // newClient.setUser(user);
    return new ResponseEntity<Client>(clientservices.save(newClient), HttpStatus.CREATED);
}

With that function, it adds a null value in the Client table.

Can someone help me, please?

PS: I use the spring security system.

ikos23
  • 4,879
  • 10
  • 41
  • 60
BaNRoOt
  • 3
  • 4
  • Possible duplicate of [When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?](https://stackoverflow.com/questions/248562/when-using-spring-security-what-is-the-proper-way-to-obtain-current-username-i) – dur May 02 '18 at 14:53

1 Answers1

0

With Spring Security, you can get the logged client through SecurityContextHolder.getContext().getAuthentication()

and you can get various details from:

  • getPrincipal() - usually the user identifier
  • getAuthorities() - the authorities
  • getDetails() - additional user details

The infos put in the various fields depends how spring security handle your authentication mecanism, but I guess you can find what you need for in principal.

slemoine
  • 367
  • 3
  • 8
  • Thanks for your answer @slemoine . I have used **getPrincipal()**...Indeed, it retrieves every details about the currentUser except the **ID**. And this is the attribute i actually need. – BaNRoOt May 03 '18 at 08:58
  • Well I guess if you have the username which should be unique or email, you can retrieve it from database then – slemoine May 03 '18 at 09:00