Back to all

How to enable OAuth 2.0 for Mosquitto MQTT Broker – Quick guide

In the modern digital age, the OAuth 2.0 frameworks help ensure secure and efficient Internet interactions. They provide a standardized method for users to authorize applications to access resources without sharing sensitive credentials.

Using Pro Edition for Eclipse Mosquitto™ with the JWT plugin enables OAuth2.0 authorization flows to build secure and efficient information exchanges. Integrating MQTT with IAM solutions like Keycloak, Okta, Azure, Google, AWS, and GitHub improves security and user experience. These IAM solutions support OAuth 2.0 for secure authentication and authorization. This article presents a flexible scenario using the Pro Mosquitto broker’s capabilities. The broker authenticates the connection using JSON web tokens (JWT), making it suitable for a wide range of use cases, from smart home applications to industrial automation.

What is OAuth 2.0?

In 2012, the Internet Engineering Task Force (IETF) published RFC 6749 and RFC 6750, formalizing OAuth 2.0 as an authorization framework. Many organizations widely use this approach to authorize access to digital resources, particularly for REST APIs implemented over HTTP. The key benefit is that an OAuth 2.0-capable Identity-Access-Management (IAM) solution acts as a trusted mediator, as shown in Figure 1. 

The client or device seeking access to a digital resource — here, the MQTT broker — only needs to request authorization. The different types of authorization flows will involve user consent and end in using a valid JWT for the broker connection.

Example for Device Authorization Grant

Figure 1 – Example flow for Device Authorization Grant to derive a JWT from the IAM solution (Every OAuth2.0 flow is compatible with the JWT plugin for Pro Mosquitto).

MQTT & OAuth 2.0

The need to standardize access control for web APIs (now mostly REST APIs) drove the development of the open authorization framework – OAuth 2.0. Developers use such APIs to access webmail, cloud storage, messengers, etc. The standard realizes a seamless user experience for single sign-on for services from different providers. For instance, you can use your Google account to sign up for the Cedalo MQTT Platform trial. All these APIs and services use HTTP and, therefore, the exchange of credentials and tokens is also done using HTTP.

The Pro Mosquitto’s JWT plugin enables secure authentication of MQTT clients using the OAuth 2.0 compatible IAM solution. Therefore, the plugin verifies the JWT signature and checks the validity of the token (introspection) using HTTP and the OAuth 2.0 IAM solution (refer to Figure 1). Pro Mosquitto’s JWT plugin seamlessly integrates with existing authorization frameworks, even though OAuth 2.0 was originally not designed for MQTT authentication.

OAuth 2.0 Grant Types

The OAuth framework specifies several grant types for different use cases. Some of the most common OAuth grant types are:

  • Authorization Code
  • Authorization Code with Proof Key for Code Exchange (PKCE)
  • Device Authorization Code

Many use cases for OAuth2.0 implement single sign-on user experiences for web-based services. Therefore, the Authorization Code grant type is suitable for backend applications that securely store application or client secrets. This type of backend application redirects requests to the IAM solution and finally retrieves the JWT to access the protected resources on behalf of the authenticated user. The specific resource capabilities are authorized by requesting the user’s consent to particular scopes. For example, "read.traffic" or "read.all.traffic." The second grant type, the authorization code flow with PKCE, is used for front-end or single-page applications (SPA). Due to the nature of these applications running in a browser, they cannot store shared secrets securely.

The last grant type listed above is the Device Authorization Code. This approach is suitable for applications/devices that have limited user interaction capabilities like keyboards or touch screens. It offloads the user interaction – logging in with credentials – to a user device, such as a smartphone.
All of the listed grant types are compatible with Pro Mosquitto’s JWT plugin, enabling a wide range of possible use cases.

Grant Type Client Credentials

All the grant types I mentioned previously require user or human interaction. With the Client Credentials grant type, the device/application (see Figure 1) can directly acquire a JWT from the OAuth 2.0 IAM solution. It is used by clients (= devices/applications) to obtain a JWT outside of a user’s context. This skips the step that a user needs to authenticate. However, the client credentials (= client_id and client_secret) must be stored on the device/application. So, the security differences between using this grant type and the standard username/password for MQTT clients are minimal.

The choice of authorization flows and grant types depends on the use case and device capabilities. In the following section, I describe a complete example use case with a detailed setup.

OAuth 2.0 example use case for Pro Mosquitto MQTT broker

Assume we have a generic smart device that can connect to the Internet via NB-IoT and display a URL as a QR code. Assume that the device’s purpose is to publish its own state values and respond to external events (subscribe to topics). An MQTT broker enables communication and message exchange between the devices.

In the example use case, besides Pro Mosquitto trial with the JWT plugin, there is also an IAM solution (e.g. Keycloak). The IAM requires to have at least one user with the name cedalo and an OAuth 2.0 client with the name mqtt-device. Also, the Device Authorization Code the grant type shall be enabled in the IAM settings. Following the onboarding sequence shown in Figure 1, the device is powered up and connects to the IAM solution via NB-IoT. More specifically, after initialization, the device makes the following POST request:

curl -X POST \
https://<YOUR-KEYCLOAK>/realms/<REALM-NAME>/protocol /openid-connect/auth/device \
--data “client_id=<YOUR-CLIENT-ID>”

Note that the “<YOUR-CLIENT-ID>” in this context of OAuth2.0 is a different id than the client_id in the context of MQTT. In the context of OAuth2.0, this is also called “app-id.” The value <REALM-NAME> is the name chosen to name the organization or group.

The response will be as follows (example):

{
'device_code': 'devcode4711',
'user_code': 'JXLR-GIXD',
'verification_uri_complete':'https://<YOUR-KEYCLOAK>/JXLR_GIXD...'
}

The system encodes the resulting verification URI in a QR code and displays it for the user. The user takes a smart mobile, follows the QR code link, logs in, and gives the consent that the IAM shall grant access for this device to retrieve access and refresh tokens (JWT).

During the time the user logs in and gives consent for the device, the device application polls in a loop requests to retrieve the tokens (JWT) with:

curl -X POST \
https://<YOUR-KEYCLOAK>/realms/<REALM-NAME>/protocol/openid-connect/token \
--data “client_id=<YOUR-CLIENT-ID>\
&grant_type=urn:ietf:params:oauth:grant-type:device_code\
&device_code=devcode4711”

If the user has not yet finished the login procedure, the device receives the following answer from the IAM solution:

{
 'error': 'authorization_pending',
 'error_description': 'The authorization request is still pending'
}

If the user completes the login procedure, the device receives the tokens (for example, shortened tokens).

{
 'access_token': 'eyJhb...',
 'expires_in': 600,
 'refresh_expires_in': 3600,
 'refresh_token': 'eyJhbGc...',
}

Now, the application uses the access token (JWT) received from the hardware and the unique device serial number to connect to the Pro Mosquitto MQTT broker.

As an example, you can do this using the command (for demonstration purposes only, neglecting host, port, and TLS):

mosquitto_pub -u cedalo -P eyJhb... \
-i serial4711 \
-t devices/serial4711/state \
-m online

The username (-u) is cedalo, the password (-P) is the access token (JWT) from the previous request, and the client-id (-i) is the serial number in that example use case. The broker acknowledges the connection after verifying the token. It further grants access for the client-id serial4711 to publish on the topic (-t).

In the next section, I will provide a short explanation and a link on how to set up the broker to enable this functionality.

Pro Mosquitto MQTT Broker setup for OAuth 2.0

For the general details, check out the Using JWT for the Mosquitto MQTT Broker Authentication article. Configure the JWT plugin to assign the JWT subject to the username for the use case, especially for authentication. In the JWT plugin config, set it by:

...
"common": {
    ...
    "matchUsernameToSubject": true,
    "matchClientIdToSubject": false,
    ...
},
...

For proper configuration of the introspection endpoint and public key retrieval, refer to the Using JWT fo Mosquitto MQTT Broker article.

The system acknowledges the connection after the JWT plugin confirms the token’s validity. It will use the username, taken from the token subject— in this example, ‘cedalo’— with the client ID for the authorization.

For the specific example from above, you need to:

  • Create a role named eg.: mqtt-device
  • Assign Access Control Levels (ACL)
  • Allow, publish on topic pattern: devices/%c/state/#
  • Create a user named: cedalo and assign the role: mqtt-device

The special characters “%c” in the topic pattern will ensure that the device can only publish on its own topic. According to the settings for the JWT plugin above, the system takes the username from the subject of the JWT. So, in this example setup, the device can only get access if the user who onboards it can enter the correct credentials for the user cedalo.

Wrap Up

In this article, I showed a generic use case combining the functionalities of Pro Mosquitto’s JWT plugin and OAuth2.0. As a result, I was able to grant secure access to MQTT topics for smart IoT devices. This approach provides a production-ready, scalable solution for managing thousands of devices through a centralized broker. Additionally, in the event of security issues, you can revoke sessions to disconnect devices, ensuring that no credentials are compromised.

Click to rate this post!
[Total: 1 Average: 5]
About the author
Avatar photo

Andreas Schiffler

Research Professor at the Technical University of Wuerzburg-Schweinfurt

Dr. Andreas Schiffler is a research professor at the Technical University of Wuerzburg-Schweinfurt in the field of production and data technology in mechanical engineering. In addition to research topics related to 3D metal printing, Dr. Schiffler developed a Kubernetes cluster for the practice-oriented basics of IoT and Industry 4.0 as part of the student training. Before joining the university, he worked in different product development-related positions for Siemens AG and Schaeffler AG.

His hobbies and private activities are mixed to share practical knowledge on topics like home automation driven by MQTT protocol or using open-source CNC controllers for machine tools.

Newsletters icon

Subscribe for monthly updates