# How to Configure OAuth2.0 Authentication in r-nacos: Complete Guide to Client ID, Secret, and Authorization URLs

> Configure OAuth2.0 authentication in r-nacos easily. Learn to set client ID, secret, and authorization URLs with our complete guide. Integrate with any identity provider today.

- Repository: [Nacos Group/r-nacos](https://github.com/nacos-group/r-nacos)
- Tags: how-to-guide
- Published: 2026-03-07

---

**Enable OAuth2.0 authentication in r-nacos by setting environment variables such as `RNACOS_OAUTH2_ENABLE=true`, `RNACOS_OAUTH2_CLIENT_ID`, and `RNACOS_OAUTH2_CLIENT_SECRET`, then configure the authorization, token, and userinfo URLs to integrate with your identity provider.**

r-nacos is a lightweight Rust implementation of the Nacos service registry and configuration center. Configuring **OAuth2.0 authentication in r-nacos** allows you to delegate user authentication to external identity providers (IdP) such as Keycloak, Auth0, or corporate SSO systems, eliminating the need to manage local passwords. This integration leverages the `OAuth2Manager` and `OAuth2MsgActor` components to handle the standard authorization code flow.

## How OAuth2.0 Authentication Works in r-nacos

The r-nacos OAuth2 implementation follows the standard authorization code flow. When enabled, the `OAuth2Manager` actor (defined in [`src/oauth2/core.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/oauth2/core.rs)) initializes an `OAuth2MsgActor` that constructs a `BasicClient` using your supplied configuration.

The authentication flow proceeds as follows:

1. **Authorization URL Generation**: The system generates a redirect URL to the identity provider's authorization endpoint via `OAuth2MsgReq::GetAuthorizeUrl` (implemented in [`src/oauth2/oauth2_msg_actor.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/oauth2/oauth2_msg_actor.rs) lines 24-84).
2. **Callback Handling**: After user authentication, the IdP redirects to your configured `RNACOS_OAUTH2_REDIRECT_URI`. The endpoint `/rnacos/api/console/v2/login/oauth2/login` receives the authorization code and forwards it to `OAuth2MsgReq::Authenticate`.
3. **Token Exchange**: The `OAuth2MsgActor` exchanges the code for an access token, calls the userinfo endpoint, extracts claims based on `RNACOS_OAUTH2_USERNAME_CLAIM_NAME` and `RNACOS_OAUTH2_NICKNAME_CLAIM_NAME`, and creates an internal user session stored in the Raft-backed cache.

## Environment Variables for OAuth2.0 Configuration

All OAuth2 settings are parsed from environment variables in `AppSysConfig::init_from_env()` (located in [`src/common/mod.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/common/mod.rs) lines 299-317) and exposed via `get_oauth2_config()` (lines 465-478).

| Variable | Description | Default |
|----------|-------------|---------|
| `RNACOS_OAUTH2_ENABLE` | Enable OAuth2 authentication (`true`/`false`) | `false` |
| `RNACOS_OAUTH2_SERVER_URL` | Base URL of the OAuth2 provider (used to derive default endpoints) | empty |
| `RNACOS_OAUTH2_CLIENT_ID` | OAuth2 client identifier | empty |
| `RNACOS_OAUTH2_CLIENT_SECRET` | OAuth2 client secret | empty |
| `RNACOS_OAUTH2_AUTHORIZATION_URL` | Full authorization endpoint URL | derived from `SERVER_URL` |
| `RNACOS_OAUTH2_TOKEN_URL` | Full token endpoint URL | derived from `SERVER_URL` |
| `RNACOS_OAUTH2_USERINFO_URL` | Full userinfo endpoint URL | derived from `SERVER_URL` |
| `RNACOS_OAUTH2_REDIRECT_URI` | Callback URL (e.g., `https://my-nacos.example.com/rnacos/api/console/v2/login/oauth2/login`) | empty |
| `RNACOS_OAUTH2_SCOPES` | Space-separated scopes | `"openid profile"` |
| `RNACOS_OAUTH2_USERNAME_CLAIM_NAME` | JSON field for username in userinfo response | `"username"` |
| `RNACOS_OAUTH2_NICKNAME_CLAIM_NAME` | JSON field for nickname | `"name"` |
| `RNACOS_OAUTH2_USER_DEFAULT_ROLE` | Default role for new OAuth2 users | `developer` |
| `RNACOS_OAUTH2_BUTTON` | Text for the login page button | `"OAuth2.0 登录"` |

## Step-by-Step Configuration Guide

### Setting Required Environment Variables

Configure the minimum required variables to enable OAuth2.0 authentication. You must provide the client credentials and endpoint URLs.

```bash
export RNACOS_OAUTH2_ENABLE=true
export RNACOS_OAUTH2_CLIENT_ID=your-client-id
export RNACOS_OAUTH2_CLIENT_SECRET=your-client-secret
export RNACOS_OAUTH2_AUTHORIZATION_URL=https://auth.example.com/oauth/authorize
export RNACOS_OAUTH2_TOKEN_URL=https://auth.example.com/oauth/token
export RNACOS_OAUTH2_USERINFO_URL=https://auth.example.com/oauth/userinfo

```

Alternatively, use `RNACOS_OAUTH2_SERVER_URL` as a shorthand:

```bash
export RNACOS_OAUTH2_SERVER_URL=https://auth.example.com

# The system will derive /oauth/authorize, /oauth/token, and /oauth/userinfo

```

### Configuring the Redirect URI

The `RNACOS_OAUTH2_REDIRECT_URI` must match exactly what you registered with your identity provider. This endpoint is handled by `login_api.rs::oauth2_callback`.

```bash
export RNACOS_OAUTH2_REDIRECT_URI=https://my-nacos.example.com/rnacos/api/console/v2/login/oauth2/login

```

### Customizing User Claims and Roles

Map the identity provider's userinfo response fields to r-nacos internal user attributes:

```bash
export RNACOS_OAUTH2_USERNAME_CLAIM_NAME=sub          # If using 'sub' as unique ID

export RNACOS_OAUTH2_NICKNAME_CLAIM_NAME=display_name
export RNACOS_OAUTH2_USER_DEFAULT_ROLE=admin          # Or developer, guest, etc.

export RNACOS_OAUTH2_SCOPES="openid profile email"

```

## Code Examples

### Docker Compose Configuration

Deploy r-nacos with OAuth2.0 authentication using Docker Compose:

```yaml
services:
  r-nacos:
    image: nacos-group/r-nacos:latest
    environment:
      - RNACOS_OAUTH2_ENABLE=true
      - RNACOS_OAUTH2_CLIENT_ID=abc123
      - RNACOS_OAUTH2_CLIENT_SECRET=super-secret
      - RNACOS_OAUTH2_AUTHORIZATION_URL=https://auth.example.com/oauth/authorize
      - RNACOS_OAUTH2_TOKEN_URL=https://auth.example.com/oauth/token
      - RNACOS_OAUTH2_USERINFO_URL=https://auth.example.com/oauth/userinfo
      - RNACOS_OAUTH2_REDIRECT_URI=https://my-nacos.example.com/rnacos/api/console/v2/login/oauth2/login
      - RNACOS_OAUTH2_SCOPES=openid profile email
      - RNACOS_OAUTH2_USERNAME_CLAIM_NAME=sub
      - RNACOS_OAUTH2_NICKNAME_CLAIM_NAME=name
      - RNACOS_OAUTH2_USER_DEFAULT_ROLE=developer
      - RNACOS_OAUTH2_BUTTON="Login with ExampleIDP"
    ports:
      - "8848:8848"
      - "9848:9848"

```

### Authorization URL Generation (Rust Implementation)

The `OAuth2MsgActor` generates the authorization URL using the `oauth2` crate's `BasicClient`. Here is how the internal API works:

```rust
use crate::oauth2::model::actor_model::OAuth2MsgReq;
use crate::oauth2::model::OAuth2MsgResult;

// Within an async context (e.g., login config endpoint)
let result = oauth2_manager
    .send(OAuth2MsgReq::GetAuthorizeUrl)
    .await?;

if let Ok(OAuth2MsgResult::AuthorizeUrl(url)) = result {
    println!("Redirect user to: {}", url);
}

```

This corresponds to the implementation in [`src/oauth2/oauth2_msg_actor.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/oauth2/oauth2_msg_actor.rs) lines 24-84, where the actor constructs the URL using `client.authorize_url()` with PKCE and the configured scopes.

### Handling the OAuth2 Callback (Rust Implementation)

When the identity provider redirects back to r-nacos, the callback handler extracts the authorization code and exchanges it for a user session:

```rust
use crate::oauth2::model::actor_model::{OAuth2MsgReq, OAuth2UserParam};

let code = query_params.code.clone();
let state = query_params.state.clone();

let resp = oauth2_manager
    .send(OAuth2MsgReq::Authenticate(OAuth2UserParam { code, state }))
    .await?;

match resp {
    Ok(OAuth2MsgResult::UserMeta(meta)) => {
        // meta contains user_name, role, namespace_privilege
        // Create session, store in Raft-backed cache, set cookies
        // See login_api.rs::oauth2_callback for full implementation
    }
    Ok(OAuth2MsgResult::None) => {
        // Authentication failed – invalid code or state
    }
    _ => {
        // Unexpected error
    }
}

```

## Key Source Files and Architecture

Understanding the r-nacos OAuth2 implementation requires familiarity with these specific files:

| File | Purpose |
|------|---------|
| [`src/common/mod.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/common/mod.rs) | Parses all `RNACOS_OAUTH2_*` environment variables in `AppSysConfig::init_from_env()` (lines 299-317) and exposes `get_oauth2_config()` (lines 465-478). |
| [`src/oauth2/core.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/oauth2/core.rs) | Defines the **OAuth2Manager** actor that manages the OAuth2 lifecycle and communication with the message actor. |
| [`src/oauth2/oauth2_msg_actor.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/oauth2/oauth2_msg_actor.rs) | Implements **OAuth2MsgActor** containing the core logic: building `BasicClient`, generating authorize URLs (`GetAuthorizeUrl`), and exchanging codes for tokens (`Authenticate`) lines 24-84. |
| [`src/console/login_api.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/console/login_api.rs) | HTTP API endpoints: `get_login_config` (returns OAuth2 button text and URL) and `oauth2_callback` (handles IdP redirect, lines 6-25). |
| [`src/starter.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/starter.rs) | Registers `OAuth2Manager` as a bean during application startup. |
| `src/oauth2/model/*.rs` | Data structures for `OAuth2Config`, `OAuth2MsgReq`, `OAuth2MsgResult`, and user metadata. |

## Summary

Configuring **OAuth2.0 authentication in r-nacos** requires setting environment variables that define your identity provider endpoints, client credentials, and user claim mappings. The system implements a standard authorization code flow through the `OAuth2Manager` and `OAuth2MsgActor` actors, handling URL generation, token exchange, and user session creation automatically.

- **Enable OAuth2** by setting `RNACOS_OAUTH2_ENABLE=true` and providing `CLIENT_ID`, `CLIENT_SECRET`, and endpoint URLs.
- **Configure endpoints** using either `RNACOS_OAUTH2_SERVER_URL` as a base or specific `AUTHORIZATION_URL`, `TOKEN_URL`, and `USERINFO_URL` variables.
- **Map user claims** using `RNACOS_OAUTH2_USERNAME_CLAIM_NAME` and `RNACOS_OAUTH2_NICKNAME_CLAIM_NAME` to match your IdP's response format.
- **Customize the UI** with `RNACOS_OAUTH2_BUTTON` to change the login page button text.
- **Reference implementation** files include [`src/common/mod.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/common/mod.rs) for configuration, [`src/oauth2/oauth2_msg_actor.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/oauth2/oauth2_msg_actor.rs) for flow logic, and [`src/console/login_api.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/console/login_api.rs) for HTTP endpoints.

## Frequently Asked Questions

### What environment variables are required to enable OAuth2.0 in r-nacos?

At minimum, you must set `RNACOS_OAUTH2_ENABLE=true`, `RNACOS_OAUTH2_CLIENT_ID`, `RNACOS_OAUTH2_CLIENT_SECRET`, and the endpoint URLs (`RNACOS_OAUTH2_AUTHORIZATION_URL`, `RNACOS_OAUTH2_TOKEN_URL`, `RNACOS_OAUTH2_USERINFO_URL`). Alternatively, set `RNACOS_OAUTH2_SERVER_URL` to derive the default endpoint paths automatically.

### How does r-nacos handle the OAuth2 callback and user session creation?

When the identity provider redirects to your configured `RNACOS_OAUTH2_REDIRECT_URI`, the endpoint defined in [`src/console/login_api.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/console/login_api.rs) extracts the authorization code and state, then sends an `OAuth2MsgReq::Authenticate` message to the `OAuth2Manager`. The `OAuth2MsgActor` exchanges the code for tokens, calls the userinfo endpoint, maps the JSON claims to internal user metadata using `RNACOS_OAUTH2_USERNAME_CLAIM_NAME`, and creates a session stored in the Raft-backed cache.

### Can I customize which user attributes are used for the username and display name?

Yes. Set `RNACOS_OAUTH2_USERNAME_CLAIM_NAME` to specify which field in the userinfo JSON response contains the unique username (common values include `sub`, `username`, or `email`). Set `RNACOS_OAUTH2_NICKNAME_CLAIM_NAME` to specify the display name field (commonly `name` or `display_name`). These mappings are applied in [`src/oauth2/oauth2_msg_actor.rs`](https://github.com/nacos-group/r-nacos/blob/main/src/oauth2/oauth2_msg_actor.rs) when constructing the internal user metadata.

### What is the default role assigned to new users authenticated via OAuth2?

By default, new users created through OAuth2 authentication are assigned the role specified in `RNACOS_OAUTH2_USER_DEFAULT_ROLE`, which defaults to `developer` if not explicitly set. You can change this to `admin`, `guest`, or any custom role defined in your r-nacos deployment to control the initial permissions granted to federated users.