Raymond
Raymond

Reputation: 3462

jquery/ajax call to webapi and URL encoding with backslash

For purely debugging/testing/hack reasons, I have an html page that takes in a username - e.g. MyDomain\JohnDoe and authenticates the user.

My question is, how do I send/encode and setup the webapi routes/decode the full username with the backslash \? I tried encodeURIComponent that changse the \ into %5C, but then the webapi routes don't work. If I leave off the \, then the routes work and the action method is hit.

HTML PAGE: $('#authenticate').click(function () {

            var username = encodeURIComponent($('#username').val());
            var password = encodeURIComponent($('#password').val());
            var uri = 'http://localhost/api/tester/' + username + '/' + password;
            $.ajax({
                url: uri;
                type: 'GET',
                dataType: 'json',
                success: function (data, textStatus, xhr) {
                    $('#authenticationMessage').text(data);
                },
                error: function (xhr, textStatus, err) {
                    $('#authenticationMessage').text('Error: ' + err + ' --   ' + uri);
                }
            });
        });

CONTROLLER:

[RoutePrefix("api/tester")
public class AuthenticationClientTesterController : ApiController
{
    [Route("{username}/{password}", Name = "GetAuthenticatedTester")]
    public async Task<string> GetAuthenticated(string username, string password)
    {
        string message = "You are NOT authenticated.  " + username;
        return message;
    }
}

Suggestions greatly welcome. Thanks.

Upvotes: 0

Views: 1811

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039328

You totally should forget about sending special characters in the path portion of an url as Scott Hanselman explains in this blog post: http://www.hanselman.com/blog/ExperimentsInWackinessAllowingPercentsAnglebracketsAndOtherNaughtyThingsInTheASPNETIISRequestURL.aspx

I will only quote his conclusion that should put you on the right track of what you should be doing:

After ALL this effort to get crazy stuff in the Request Path, it's worth mentioning that simply keeping the values as a part of the Query String (remember WAY back at the beginning of this post?) is easier, cleaner, more flexible, and more secure.

So, encodeURIComponent is great for sending values as query string parameters or POST values which is how usernames and passwords should be sent.

Upvotes: 3

Related Questions