How to set status codes such as 401 and 403?

The same way you would in any other PHP program:

header("HTTP/1.1 401 Unauthorized");
exit;

WordPress has special handling for 404 because there’s a 404 template. Usually if something happens such as a 401, there is no special template, but you can make use of wp_die which will show a message in a simple UI

header("HTTP/1.1 401 Unauthorized");
wp_die( 'forbidden' );

This will show the message in a white rectangle with rounded edges and sans-serif text on a gray background, then call exit/die