Yes, affiliate marketing is fully legal. In fact, it is just another way of doing marketing for companies.
Note though that each affiliate program has its own set of rules that you need to follow when promoting their products and services. This often includes restricted search engine marketing keywords and whether or not email marketing and social media marketing is allowed.
And note also that there are rules that apply to affiliate marketing like informing your readers on the same page as you promote your affiliate links that your content, in fact, contains ads / sponsored content. You should also not make false claims or fake reviews to try and sell more. Neither should you send unsolicited emails, often regarded as spam, containing affiliate marketing links.