It's illegal, unless...
You are not allowed to use an electrical product in any way contrary with its labeling and instructions.
You are also not allowed to use any electrical equipment as a support structure for ”something" e.g. Anything else. The most common blunder is hanging phone, internet or thermostat cable off Romex or conduit. I just removed some of that from a brand new furnace installation. But it also applies to using a light socket or junction box to hang a mobile, pinata, model airplane, etc.
A luminaire (light fixture/assembly) is the exception. It is allowed to hang a luminaire off a junction box, if it weighs less than six pounds. This weight can also be hung off an Edison screw base in USA (NEC 410.30A), but that seems unlikely -- far more likely you would mount it to the junction box.
A heavier luminaire can be hung off a special junction box made for that purpose.
An even more special junction box is made for ceiling fans. A common violation is hanging a ceiling fan from a ceiling box which is not listed for ceiling fans. Aside from the unexpected weight, the problem is also vibration - I've never seen a fan that was balanced, and the vibration will eventually pry the nails out or crack the box.
The question of "leeeegal" gets super pedantic super fast due to the complexities of (especially US) law, and quickly devolves into "what do I think I can get away with" - this amounts to trying to make a simple thing complicated, with a motivation most foul: trying to cheat safety. So let us cleave this Gordian knot with a more basic question: Is there any competent regulatory agency in the world which on fair contemplation, chooses to explicitly authorize general use of electrical equipment contrary to its listing, labeling and instructions? I assert you will not.