I’m no Symfony expert, I write what I find as I find it. Nothing in the documentation really covers this subject, so I am not sure what the correct way is of if there even is one. Getting the User ID is way harder than it ever should be to be perfectly honest.
There are a few ways I have found to get a user id. None of the classes you can inject such as UserInterface, SessionInterface, TokenInterface, Security etc. contain an actual getUserId() method. There is absolutely no method named this other than in the user Entity, if your entity contains a column named id.
You can get a user object from the Security class, as seen in the documentation here. To do so you type hint aka Dependency Inject your service constructor with Security but not just any Security will do, there is also one by Sensio labs and another. Be careful what you you choose when your IDE suggests a list. You want this Security
Then your ide wont show the getId() method, or will warn something about a polymorphic call blah blah. But there is a getId() method of the user Entity returned from Security and you can get a user id like this.
/** @var User $user */
$user = $this->security->getUser()->getId();
$userId = $user->getId();
This method may return null if the user is not logged in so you need to check for that. The @var syntax tells the IDE what is going on so it knows there is a getId() method, you will also need to import that class. The User object it refers to is your App/Entity/User class.
Forgive me if anything is wrong. I wish there was more info about this since this is one of the most popular articles on this site
Link to a Symfony cast with a little more info but not much.