MichaelJones
MichaelJones

Reputation: 1406

Sanitize user input for inclusion in href attribute?

I would like to accept a user inputted url and display it in the href attribute part of the link tag. ie.

<a href="%(user_input)s">My link name</a>

But I would like to make sure that it doesn't have any malicious content as far as inject script tags and the like. What is the best approach to sanitizing the user_input part?

From what I can tell:

Perhaps the best approach is urlquote_plus with some safe characters specified?

Upvotes: 2

Views: 2554

Answers (2)

MichaelJones
MichaelJones

Reputation: 1406

I was over thinking the problem. It turns out that using django.utils.html.escape is fine as it results in HTML that has link tags with an href attributes which might have &amp; in them instead of & but the browser handles this fine.

I thought I needed to find a way to have & in there as urls don't have &amp; in them.

My final code is:

from django.utils.safestring import mark_safe
from django.utils.html import escape

....

output = '<li><a href="%s">%s</a></li>' \
   % (escape(entry['url']), escape(self.link_display(entry)))

return mark_safe(output)

Upvotes: 0

abhi
abhi

Reputation: 366

You can use the template tag: safe.

Let's say that your post context variable is:

user_input = some_valid_url

Grab user_input, and add the html to make it a link and reinsert it when saving the post. So the saved post is:

link_text = <a href=user_input>Link</a>

And then use safe in your html template:

{{ link_text|safe }}

Here is the documentation link for safe template tags: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#safe

Upvotes: 1

Related Questions