It's large topic. Here I intend to share some details w/o too much that are not needed and a good reference.
Man-in-the-Middle is not thwarted by user authentication but by server authentication. Before the user is authenticated, the server is.
That is done via Diffie-Hellman to come up with a shared secret
K and a hash, the session identifier
H. A man in the middle would need to do a DH exchange between the Client and themself and themself and the Server. Both of those outputs will be guaranteed to be different.
The server signs the session identifier
H with it's private key. The client verifies it with the server's public key. Keep in mind it's trust on first use so it's open to MITM until the public key is associated to the specific server (i.e known_hosts in openssh/etc).
The RFC has more details.