通过外部URL允许图像配置文件的最佳安全方式[关闭]

Suppose that I have a web application where users can attach a link in their profile to show the avatar (displayed after with img tag).

This is safe? I think it is not.

What is the best way to check if the url provided is a real image? There are other solutions? (for now I don't want any upload).

No, it is not safe. This approach is vulnerable to XSS (Cross-Site Scripting) and CSRF (Cross-Site Request Forgery) attacks. Number of ways to construct possible XSS attacks with img tags is huge. Have a look at OWASP list Malformed img tags just to give you an idea.

You may say that escaping can help you. Yes it is, but escaping alone does not guarantee XSS prevention. Here is what OWASP (The Open Web Application Security Project) recommends in general:

You MUST use the escape syntax for the part of the HTML document you're putting untrusted data into

Plus check what data is allowed (white list) instead of checking endless list of not allowed data. Here is OWASP's XSS prevention cheat sheet. OWASP also released a library ESAPI to be used for escaping in the right context.

But let's say you are done with XSS. With CSRF malicious user can construct legitimate request inside your img tag for updating some user's profile. And let's say such user comes to see this profile and all of the sudden his/her profile is updated! In this case you will probably need to generate "challenge" / validation token associated with user's session which will be attached to each user's request.

My recommendation is either use external trusted service like gravatar or implement upload. If you do want to use user's input then I strongly encourage you to familiarize yourself with ESAPI library for this case and OWASP XSS and CSRF prevention cheat sheets.

if you use urlEncode() + urlDecode() no problem

I think you're asking for a safe way for users to upload a photo with their profile.

If you do not want to deal with it, check out https://gravatar.com/ where they manage the user's profile picture.

Github uses them.