How To Perform Authorization Checks

Preconditions

The following conditions are assumed:

  1. You have the sources of a contract with one of the actions defined, let's call it hi action.
  2. The hi action has defined one input parameter user of type name.
  3. The hi action prints the name of the user account.
  4. The hi action needs to authorize the user account.

Authorization Methods

To restrict access to the hi action, you can do it in three ways.

1. Use eosio::check(eosio::has_auth(...)...)

The below code enforces the action hi to be executed only by the account that is sent as parameter to the action, no matter what permission the account uses to sign the transaction (e.g. owner, active, code).

Error message is custom

Observe that in this case the yielded error message is a custom one and thus it can be used to provide a better experience for the user.

#include <capi/eosio/action.h>

void hi( name user ) {
   check(has_auth(user), "User is not authorized to perform this action.");
   print( "Hello, ", name{user} );
}

Another example can be found in the Tic Tac Toe Tutorial.

2. Use require_auth

The below code enforces the action hi to be executed only by the account that is sent as parameter to the action, no matter what permission the account uses to sign the transaction (e.g. owner, active, code).

void hi( name user ) {
   require_auth( user );
   print( "Hello, ", name{user} );
}
Error message is not custom

Note that this time you can not customize the yielded error message, it will be a generic authorization error message.

3. Use require_auth2

The below code is enforces the action hi to be executed only by the account that is sent as parameter to the action and only if the permission used to sign the transaction is the 'active' one. In other words, if the same user uses the transaction with a different permission (e.g. code, owner) the execution of the action is halted.

#include <capi/eosio/action.h>

void hi( name user ) {
   require_auth2(user.value, "active"_n.value);
   print( "Hello, ", name{user} );
}
Error message is not custom

Note that this time, as well as previous method, you can not customize the yielded error message, it will be a generic authorization error message.