Access Control - OpenZeppelin Docs (2024)

Access control—that is, "who is allowed to do this thing"—is incredibly important in the world of smart contracts. The access control of your contract may govern who can mint tokens, vote on proposals, freeze transfers, and many other things. It is therefore critical to understand how you implement it, lest someone else steals your whole system.

Ownership and Ownable

The most common and basic form of access control is the concept of ownership: there’s an account that is the owner of a contract and can do administrative tasks on it. This approach is perfectly reasonable for contracts that have a single administrative user.

OpenZeppelin provides Ownable for implementing ownership in your contracts.

pragma solidity ^0.5.0;import "@openzeppelin/contracts/ownership/Ownable.sol";contract MyContract is Ownable { function normalThing() public { // anyone can call this normalThing() } function specialThing() public onlyOwner { // only the owner can call specialThing()! }}

By default, the owner of an Ownable contract is the account that deployed it, which is usually exactly what you want.

Ownable also lets you:

  • transferOwnership from the owner account to a new one, and

  • renounceOwnership for the owner to relinquish this administrative privilege, a common pattern after an initial stage with centralized administration is over.

Removing the owner altogether will mean that administrative tasks that are protected by onlyOwner will no longer be callable!

Note that a contract can also be the owner of another one! This opens the door to using, for example, a Gnosis Multisig or Gnosis Safe, an Aragon DAO, an ERC725/uPort identity contract, or a totally custom contract that you create.

In this way you can use composability to add additional layers of access control complexity to your contracts. Instead of having a single regular Ethereum account (Externally Owned Account, or EOA) as the owner, you could use a 2-of-3 multisig run by your project leads, for example. Prominent projects in the space, such as MakerDAO, use systems similar to this one.

Role-Based Access Control

While the simplicity of ownership can be useful for simple systems or quick prototyping, different levels of authorization are often needed. An account may be able to ban users from a system, but not create new tokens. Role-Based Access Control (RBAC) offers flexibility in this regard.

In essence, we will be defining multiple roles, each allowed to perform different sets of actions. Instead of onlyOwner everywhere - you will use, for example, onlyAdminRole in some places, and onlyModeratorRole in others. Separately, you will be able to define rules for how accounts can be assignned a role, transfer it, and more.

Most of software development uses access control systems that are role-based: some users are regular users, some may be supervisors or managers, and a few will often have administrative privileges.

Using Roles

OpenZeppelin provides Roles for implementing role-based access control. Its usage is straightforward: for each role that you want to define, you’ll store a variable of type Role, which will hold the list of accounts with that role.

Here’s a simple example of using Roles in an ERC20 token: we’ll define two roles, minters and burners, that will be able to mint new tokens, and burn them, respectively.

pragma solidity ^0.5.0;import "@openzeppelin/contracts/access/Roles.sol";import "@openzeppelin/contracts/token/ERC20/ERC20.sol";import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";contract MyToken is ERC20, ERC20Detailed { using Roles for Roles.Role; Roles.Role private _minters; Roles.Role private _burners; constructor(address[] memory minters, address[] memory burners) ERC20Detailed("MyToken", "MTKN", 18) public { for (uint256 i = 0; i < minters.length; ++i) { _minters.add(minters[i]); } for (uint256 i = 0; i < burners.length; ++i) { _burners.add(burners[i]); } } function mint(address to, uint256 amount) public { // Only minters can mint require(_minters.has(msg.sender), "DOES_NOT_HAVE_MINTER_ROLE"); _mint(to, amount); } function burn(address from, uint256 amount) public { // Only burners can burn require(_burners.has(msg.sender), "DOES_NOT_HAVE_BURNER_ROLE"); _burn(from, amount); }}

So clean! By splitting concerns this way, much more granular levels of permission may be implemented than were possible with the simpler ownership approach to access control. Note that an account may have more than one role, if desired.

OpenZeppelin uses Roles extensively with predefined contracts that encode rules for each specific role. A few examples are: ERC20Mintable which uses the MinterRole to determine who can mint tokens, and WhitelistCrowdsale which uses both WhitelistAdminRole and WhitelistedRole to create a set of accounts that can purchase tokens.

This flexibility allows for interesting setups: for example, a MintedCrowdsale expects to be given the MinterRole of an ERC20Mintable in order to work, but the token contract could also extend ERC20Pausable and assign the PauserRole to a DAO that serves as a contingency mechanism in case a vulnerability is discovered in the contract code. Limiting what each component of a system is able to do is known as the principle of least privilege, and is a good security practice.

Usage in OpenZeppelin

You’ll notice that none of the OpenZeppelin contracts use Ownable. Roles is a prefferred solution, because it provides the user of the library with enough flexibility to adapt the provided contracts to their needs.

There are some cases, however, where there’s a direct relationship between contracts. For example, RefundableCrowdsale deploys a RefundEscrow on construction, to hold its funds. For those cases, we’ll use Secondary to create a secondary contract that allows a primary contract to manage it. You could also think of these as auxiliary contracts.

← Overview

Tokens →

Access Control - OpenZeppelin Docs (2024)

FAQs

How to use OpenZeppelin access control? ›

OpenZeppelin provides Roles for implementing role-based access control. Its usage is straightforward: for each role that you want to define, you'll store a variable of type Role , which will hold the list of accounts with that role.

What is the difference between ownable and access control? ›

AccessControl provides a general role based access control mechanism. Multiple hierarchical roles can be created and assigned each to multiple accounts. Ownable is a simpler mechanism with a single owner "role" that can be assigned to a single account.

What is the difference between _setupRole and _grantrole? ›

_setupRole(bytes32 role, address account) internal

Grants role to account . If account had not been already granted role , emits a RoleGranted event. Note that unlike grantRole , this function doesn't perform any checks on the calling account.

What is access control and why is it important in Solidity? ›

Access control is a critical aspect of smart contract security, governing who can interact with various functionalities within the contract. However, improper implementation of access control can lead to severe vulnerabilities, allowing unauthorized users to manipulate the contract's state or even drain its funds.

How do you use access control? ›

In its simplest form, access control involves identifying a user based on their credentials and then authorizing the appropriate level of access once they are authenticated. Passwords, pins, security tokens—and even biometric scans—are all credentials commonly used to identify and authenticate a user.

How does access controller work? ›

Once the card reader reads a presented credential, it sends the ID of the credential to the door controller. In the door controller resides a copy of the user database, which includes a full list of names and credentials and the access permissions that each person has.

What are the three 3 types of access control? ›

The 3 types of access control are Role-Based Access Control (RBAC) systems, Attribute-Based Access Control (ABAC) and Discretionary Access Control (DAC). Each of the three access control types can be leveraged to ensure that your property and data is secure.

What is the strongest form of access control? ›

Mandatory access control systems are the most secure type of access control. They're also the most inflexible as they only allow the system's owner or administrator to control and manage access. People are given access based on different security levels and information clearance.

Which access control is easiest? ›

SimpliSafe is one of the most simple and easy-to-use business access control systems. This access control system is extremely easy to set up, comes with free professional installation, and monitors your premises 24/7.

What is the main reason for access control? ›

Why is access control important? The goal of access control is to minimize the security risk of unauthorized access to physical and logical systems.

Which three elements are needed for access control? ›

Three elements make up access control: identification, authentication, and authorization. The world of information security is vast. There are many different kinds of attacks and various defenses against them.

What is the key point of access control? ›

The main purpose of access control is to provide a secure environment. Physical access control systems regulate who can enter particular areas, buildings, or rooms. But it's not just about keeping unauthorized people out; it's also about managing and monitoring the flow of people and assets within controlled areas.

What is access control mode? ›

Access Control Models allow organizations to grant user permissions and enforce access policies. There are four types of access control methods: Mandatory Access Control (MAC), Role-Based Access Control (RBAC), Discretionary Access Control (DAC), and Rule-Based Access Control (RBAC or RB-RBAC).

What is the RBAC model? ›

Role-based access control (RBAC) refers to the idea of assigning permissions to users based on their role within an organization. It offers a simple, manageable approach to access management that is less prone to error than assigning permissions to users individually.

How to use ownable in Solidity? ›

Ownable contracts in Solidity are used to implement access control for certain functions. The idea is that only the contract owner, who is typically the deployer of the contract, can execute these protected functions. import "@openzeppelin/contracts//contracts/access/Ownable.

Top Articles
18 Reasons to Visit Stockholm & Why You'll Love It
Blog — Sisters for Financial Independence
Combat level
Canary im Test: Ein All-in-One Überwachungssystem? - HouseControllers
Ghosted Imdb Parents Guide
Otterbrook Goldens
Fnv Turbo
Hardly Antonyms
Which Is A Popular Southern Hemisphere Destination Microsoft Rewards
123Moviescloud
VMware’s Partner Connect Program: an evolution of opportunities
Apne Tv Co Com
Cpt 90677 Reimbursem*nt 2023
Spectrum Field Tech Salary
Copart Atlanta South Ga
Stardew Expanded Wiki
Royal Cuts Kentlands
Evil Dead Rise Showtimes Near Regal Sawgrass & Imax
Violent Night Showtimes Near Century 14 Vallejo
Tips and Walkthrough: Candy Crush Level 9795
Low Tide In Twilight Ch 52
Victory for Belron® company Carglass® Germany and ATU as European Court of Justice defends a fair and level playing field in the automotive aftermarket
Roanoke Skipthegames Com
Gen 50 Kjv
Taylored Services Hardeeville Sc
Www.1Tamilmv.con
Delta Rastrear Vuelo
Kltv Com Big Red Box
Adecco Check Stubs
Morlan Chevrolet Sikeston
Netherforged Lavaproof Boots
RUB MASSAGE AUSTIN
Www Violationinfo Com Login New Orleans
Rocketpult Infinite Fuel
Panchitos Harlingen Tx
4083519708
Bay Focus
Hisense Ht5021Kp Manual
Avance Primary Care Morrisville
Boggle BrainBusters: Find 7 States | BOOMER Magazine
Pawn Shop Open Now
World History Kazwire
Ktbs Payroll Login
My Locker Ausd
War Room Pandemic Rumble
Zipformsonline Plus Login
Aloha Kitchen Florence Menu
Take Me To The Closest Ups
The Goshen News Obituary
Mkvcinemas Movies Free Download
Where To Find Mega Ring In Pokemon Radical Red
Who We Are at Curt Landry Ministries
Latest Posts
Article information

Author: Clemencia Bogisich Ret

Last Updated:

Views: 6523

Rating: 5 / 5 (60 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Clemencia Bogisich Ret

Birthday: 2001-07-17

Address: Suite 794 53887 Geri Spring, West Cristentown, KY 54855

Phone: +5934435460663

Job: Central Hospitality Director

Hobby: Yoga, Electronics, Rafting, Lockpicking, Inline skating, Puzzles, scrapbook

Introduction: My name is Clemencia Bogisich Ret, I am a super, outstanding, graceful, friendly, vast, comfortable, agreeable person who loves writing and wants to share my knowledge and understanding with you.