简体   繁体   中英

Object.defineProperty - prevent user changing this JavaScript

I want to check in my webapp if a user is admin.

  var obj = { admin: false; };

  Object.defineProperty(obj, "admin", {
      writable: false
  });

Now, a user can go into the console, and do:

Object.defineProperty(obj, "admin", {
          writable: true
      });

obj.admin = true;

Is there a way to prevent this? Is there another best way to prevent executing parts of JavaScript code if a certain criteria applies? I understand, users could alter the code anyway, so I am a bit looking for good practices.

No. You can't prevent users (like me) from running my own javascript on my OWN browser. You need to validate, authenticate and authorize on the server-side. To authenticate and authorize a request you need to use standard mechanisms such as cookies, tokens, api access keys, etc.

You can create properties on objects that cannot be changed by using Object.defineProperty . Run the snippet below and you will see TypeError: Cannot redefine property: admin in the console.

 const User = {}; Object.defineProperty( User, "admin", { value: false } ); Object.defineProperty( User, "admin", { value: true } ); 

This is because Object.defineProperty defaults to false for writable, configurable, and enumerable. Here is an except from the MDN Object.defineProperty documentation that talks about redefining existing properties.

When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false the property is said to be “non-configurable” and no attribute can be changed (besides a one-way change of writable to false). It is not possible to switch between data and accessor property types when the property is non-configurable.

All that being said, using this as a security measure will get you in trouble. As far as securing your code goes...

  1. ALWAYS validate data entering your application.
  2. Minify and obfuscate your code.
  3. Use strict mode . This will prevent a lot of unsafe practices.
  4. You can use linters to help prevent more unsafe practices.
  5. Read about common security pit falls. OWASP Top Ten is a good place to read about some of these.

You can use Object.freeze

var obj = { admin: false };
Object.freeze(obj);
obj.admin = true;
console.log(obj)

// output {admin:false}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM