Question

Not so long ago, I came across a tutorial about authentication in AngularJS. They created an AuthenticationService that looked kind of like this:

angular.module("auth").factory("AuthenticationService", function ($http, $sanitize) {

    function sanitizeCredentials(credentials) {
        return {
            username: $sanitize(credentials.username),
            password: $sanitize(credentials.password)
        };
    }

    return {
        login: function (credentials) {
            return $http.post("auth/login", sanitizeCredentials(credentials));
        }
    };
});

So as you see, the $sanitize service is used to sanitize the username as well as the password. So far so good, but does it really make sense to use it here? As far as I know, $sanitize is used when user input is immediately displayed inside html. But when I send something to the server is it really useful to sanitize it on the frontend? Since anyone can override this part, I would need to do this on the server again anyway. So why not just send it un-sanitized and do the important stuff on the backend?

Was it helpful?

Solution

Your question seems to have two parts.

Regarding $sanitize when immediately displayed, not sure what this means, b/c you'll likely have ng-model to capture the username.

Regarding sending a sanitized username / passwd from the client rather than doing it on the server, it's a reasonable question. Technically you could do either. IMO it's a matter of keeping user inputs clean at all times from the pov of your code. All inputs should be sanity checked at the earliest point. Critical pieces like credentials should have two layers of sanity, lest one inadvertently disappear. Or worse, an attack vector is discovered in one of your two (or more) sanity layers.

Recall a well-known ldap attack vector where a username reads like im-a-user)&&(). The close parens followed by an and null is an exploit. Why have such strings floating around when they could be scrubbed at the point of input?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top