User Authentication Flow

Master the complete OAuth lifecycle, from initiating the authorization request to securely exchanging cryptographic tokens within your backend architecture.

Architectural Overview

rNet utilizes the industry-standard OAuth2 Authorization Code flow with PKCE (Proof Key for Code Exchange). This sophisticated protocol ensures that cryptographic secrets remain securely on your backend, mitigating interception vulnerabilities inherent in browser-based flows.

During initiation, your system generates a randomized state token. rNet echoes this token back to your callback endpoint, allowing your backend to validate the session and categorically reject CSRF (Cross-Site Request Forgery) attacks.

Note: The following examples utilize an in-memory Map for illustrative simplicity. Production environments must utilize robust, distributed session stores like Redis.

1

Initiate Authorization

Your application triggers the login sequence. The backend generates a PKCE verifier/challenge pair, persists the verifier securely, and redirects the client to the rNet authorization gateway.
2

User Authentication

The user arrives at the rNet gateway to authenticate or register. Because this occurs exclusively on the rNet domain, your application remains securely decoupled from the user's raw credentials.
3

Consent Delegation

rNet transparently presents the permission scope requested by your application. Upon user consent, rNet mints a short-lived, single-use authorization code.
4

Code Delivery

rNet redirects the user back to your pre-registered Callback URI, appending the authorization code and the original state parameter.
5

Cryptographic Exchange

Your backend intercepts the callback and immediately transmits the authorization code alongside the original PKCE verifier to rNet's token endpoint. Upon cryptographic validation, rNet provisions the Access Token and Refresh Token.
6

Session Finalization

Your backend encrypts and stores the tokens within a secure session state before routing the user into the core application experience. The user is now fully authenticated.

Implementation Example

javascript
import crypto from 'node:crypto';
import { RNetOAuthClient, ModelClient } from '@rnet-ai/rnet-oauth-node';

const auth = new RNetOAuthClient({
  clientId: process.env.RNET_CLIENT_ID,
  clientSecret: process.env.RNET_CLIENT_SECRET,
  redirectUri: 'https://myapp.com/callback'
});

const gemini = new ModelClient('gemini-2.5-flash-lite');

// Production: Replace with Redis or secure distributed store
const stateStore = new Map();

// 1. Initiate Login
app.get('/login', (req, res) => {
  const { verifier, challenge } = auth.generatePKCE();
  const state = crypto.randomBytes(16).toString('hex');

  stateStore.set(state, { verifier, returnTo: '/dashboard' });
  setTimeout(() => stateStore.delete(state), 5 * 60 * 1000); // 5m TTL

  res.redirect(auth.getAuthorizationUrl(challenge, state));
});

// 5. Exchange Code for Tokens
app.get('/callback', async (req, res) => {
  const { code, state, error, error_description } = req.query;

  if (error) {
    return res.status(400).send(`Auth Failed: ${error} - ${error_description}`);
  }

  const stored = stateStore.get(state);
  if (!code || !stored) {
    return res.status(400).send('Invalid state payload. CSRF mitigation triggered.');
  }

  // Cryptographic exchange
  const tokens = await auth.exchangeCodeForToken(code, stored.verifier);
  stateStore.delete(state);

  req.session.rnet = {
    accessToken: tokens.access_token,
    refreshToken: tokens.refresh_token
  };

  res.redirect(stored.returnTo);
});

Universal Network Access

Once authenticated with rNet, a user's session seamlessly persists across the entire rNet ecosystem. When engaging with a new application, rNet recognizes the active session and provisions a localized authorization code without requiring redundant credential input.

All downstream AI compute costs are automatically aggregated and deducted from the user's centralized wallet, regardless of the application context.

Security Imperative
The PKCE verifier and Client Secret are highly sensitive cryptographic primitives. They must reside strictly on the backend. Never expose these variables in browser environments, mobile bundles, or public repositories. Client-side applications (SPAs) must proxy their authentication flows through an intermediary backend.

Token-Based AI Execution

The provisioned Access Token acts as the primary key for unlocking the rNet proxy network. Your application utilizes this token to execute authenticated payloads against any supported model route.

Model Routing

rNet operates as an intelligent pass-through proxy. Ensure you are targeting the exact model identifier from the supported matrix:

  • text-embedding-3-small (OpenAI)
  • gemini-2.5-flash-lite (Google)
  • gemini-3.1-flash-lite (Google)
  • gemini-2.5-flash (Google)
  • gemini-embedding-001 (Google)
  • gemma-4-26b-a4b-it (Google)
  • gemma-4-31b-it (Google)
  • llama-3.1-70b-versatile (Groq)
  • llama-3.1-8b-instant (Groq)
  • mixtral-8x7b-32768 (Groq)
  • gemma2-9b-it (Groq)

Route Protection Middleware

Implement robust middleware to ensure all AI invocation routes validate the rNet session state before allowing execution.

javascript
// Session Validation Middleware
function requireRNetSession(req, res, next) {
  if (!req.session.rnet?.accessToken) {
    return res.status(401).json({
      error: 'Unauthorized: Valid rNet session required.'
    });
  }
  next();
}

// Protected AI Route
app.post('/api/ai', requireRNetSession, async (req, res) => {
  const response = await gemini.chat(
    req.body,
    req.session.rnet.accessToken
  );
  res.json(response);
});
Next Module
Proceed to Tokens & Sign Out to understand token rotation and session termination strategies.