Dan
Dan

Reputation: 11084

Are JS variables secure from user manipulation?

I am trying to separate an tangled mess of PHP and JS. I'm not looking for perfection in the first draft but anything is better than the current state.

Current (all in one file):

<?php if( checkSecureUserStuff ): ?>
//bunch of js like including admin features
//not fun stuff
<?php endif; ?>

Proposed:

PHP file

if( checkSecureUserStuff ){
  $userAccess = 'admin';
}
...
//Later in file, I know this still not ideal
<script>
var useraccess = <?= json_encode($userAccess) ?>;
</script>

JS file

if( useraccess == 'admin' ){
  // do the admin related JS stuff here
}

Obviously in the final HTML var useraccess = 'admin'; will be visible. Is it open to manipulation at that point? I know this design isn't great, but is it terribly insecure?

Oh yea, I should mention. Actions are still checked on the server. This is more about securing the UI and keeping certain stuff disabled. The server would still verify actions.

I guess the question is more about can a user manipulate the UI if the variables are set and checked on document load. Already partially answered by millerbr's mention of setting break points . Didn't think of that

Upvotes: 1

Views: 659

Answers (1)

millerbr
millerbr

Reputation: 2961

Yes. The user will be able to open their browser console, view the code, pause it at a breakpoint they have set, and then write code in the console to edit the variable.

You should never trust your frontend for security type things - yes, write code to limit access, but always double-check on your backend and assume any requests are insecure.

There are things you can do to obscure your code and make it more difficult to manipulate, such as minifying the code, but nothing is 100% effective and so you should always assume the frontend is compromised and place the necessary precautions on any incoming data or requests.

Upvotes: 5

Related Questions