You can’t completely.
No matter what approach you take, there is some way to work around it or some dangerous failure path.
IFF tagging (mentioned by a number of other answers) can be fooled or hijacked (this has actually been an issue multiple times in the recent past).
A smart gun that only fires on identified foes can be hacked (and is still susceptible to the issues of IFF tagging).
‘Just don’t be where the bullets are going’ approaches assume intelligent troops, which is not something you should rely on (there’s a long standing joke about ‘military intelligence’ being an oxymoron, but even ignoring that stereotype mistakes can and will be made), and can just as easily be exploited by intelligent enemies.
Biological and chemical weapons have a nasty tendency to be completely indiscriminate and hard to defend against and there will generally be no way to perfectly protect your own troops (there is a reason that most of the smart militaries treated them as an absolute last resort even before they were banned by international treaty).
Even if you go really out-there sci-fi/fantasy and have omething that scans brain wave patterns, or looks at the target’s soul, or some other crazy evaluation of intrinsic properties of the target, there will probably be some way to spoof it (or some dangerous failure mode).
But even if you could, smart soldiers would not want to use it.
The issue here is that you’re introducing a couple of new ways for the weapon ti fail, no matter what weapon you are attaching this technology to, and intelligent soldiers do not like weapons that may fail to work. More specifically:
- It might misidentify a friendly target as a hostile.
- It might misidentify a hostile target as friendly.
- It might just stop working completely and brick the weapon.
The first case is somewhat scary to any soldier who relies on this system, but the second and third cases are positively terrifying to any sane soldier. A weapon that may not work at when you need it to is, in most cases worse than no weapon at all, especially if the chance of failure is relatively low. This is because most people will, in the heat of the moment, assume the weapon will work, and thus usually put themselves in a dangerous situation when it does not work.