# Using Web-server Oauth2 in Lightning Out 2.0

Next, we’ll walk through how to embed Salesforce Lightning Web Components (LWC) into a React app using Lightning Out 2.0. Essentially, this works like a simple UI mashup that brings Salesforce components directly into your React interface. Rather than starting from scratch, we’ll build right on top of the app from the previous [post](https://forcesmith.hashnode.dev/salesforce-oauth-2-0-web-server-flow-with-react-js-integration)—so if you missed it, be sure to check that out first!

Because Lightning Out 2.0 is built on the Lightning Web Runtime (LWR) rather than the older Aura framework, it works exclusively with LWCs. Security gets a major upgrade here, too, using Lightning Web Security (LWS) inside an iframe with a closed shadow DOM instead of the old Lightning Locker.

While the old beta lets unauthenticated guest users in, Lightning Out 2.0 currently requires user authentication out of the gate *(though guest user support is on the roadmap for the future as stated in the feature comparison in this* [*article*](https://developer.salesforce.com/docs/platform/lwc/guide/lightning-out-compare.html)*)*. Because of that, getting an OAuth 2.0 flow up and running is the first real hurdle we need to clear today. That's the main focus of this post, though if you want to geek out over how the two versions stack up side-by-side, check out [this guide](https://developer.salesforce.com/docs/platform/lwc/guide/lightning-out-architecture.html).

To bridge your React app with Salesforce, the `frontdoor-url` attribute on the `lightning-out-application` needs to be generated dynamically at runtime. Doing that requires an OAuth 2.0 flow that can hand you a web-scoped access token—like the web-server flow or the JWT bearer flow. For our walkthrough, we'll be using the web-server flow.

---

# Step 1: Create an External Client App (ECA)

First, set up an External Client App (ECA) to manage the OAuth 2.0 handshake between your website and Salesforce.

1. Navigate to Setup > External Client Apps.
2. Create a new app with these Critical Settings:

- Callback URL: Your website URL (e.g., <https://localhost:3006>).
  - OAuth Scopes:
  - Manage user data via APIs (api)
    - Perform requests at any time (refresh_token, offline_access)
  - Policies: Set Permitted Users to Admin approved users are pre-authorized.
  - Refresh Token Policy: Set to Valid until revoked.

3. Save and record the Consumer Key and Consumer Secret.

---

# Step 2: Configure Lightning Out 2.0

Next, configure Lightning Out 2.0 to expose your components to your external site.

1. Navigate to Setup > Lightning Out 2.0 Manager.
2. Enable the App Status.
3. Allowed Domains: Add your website domain (e.g., <https://localhost:3006>).
4. Add Component: Select the specific LWC you wish to expose.

*(Note: For a complete walkthrough of Lightning Out 2.0 setup, refer to the official Salesforce* [*documentation*](https://help.salesforce.com/s/articleView?id=platform.lightning_out_build.htm&type=5)*.)*

---

# Step 3: Update Security and Permission Settings

To prevent browsers from blocking your app due to CORS or iFrame restrictions, update these three areas in Salesforce Setup:

1. CORS: Add your domain to the Allowed List.
2. Trusted URLs: Add your domain and ensure frame-src and connect-src are permitted.
3. Trusted Domains for Inline Frames:

- Add your domain.
  - Set IFrame Type to LightningOut.

---

# Step 4: Connect Your Express App

Let's add a new endpoint to the Express app we built in the last [post](https://forcesmith.hashnode.dev/salesforce-oauth-2-0-web-server-flow-with-react-js-integration). We'll use it to grab the Salesforce frontdoor URL using the access token from our OAuth 2.0 web-server flow.

```javascript
app.get('/api/lightningoutsingleaccess', async (req, res) => {
    try {
        const response = await axios.post('https://mindful-narwhal-6i6s53-dev-ed.my.salesforce.com/services/oauth2/lightningoutsingleaccess', {
                access_token: storage.getItem('access_token'),
                lightning_out_app_id: '<your app-id here>',
            }, 
            {
                headers: { 
                    "content-type": "application/x-www-form-urlencoded"
                }
            }
        );
        res.send(response.data);
    } catch (error) {
        console.log(error);
    }
});
```

---

# Step 5: Front-end Integration (React)

The UI must load the Lightning Out script, handle the OAuth callback, and inject the custom element.

## Implementation Steps

1. Load Script: Include the Salesforce Lightning Out JS in your HTML or via a script tag: https://\[MyDomain\]/lightning/lightning.out.latest/index.iife.prod.js
2. Authorize: Redirect the user to the backend OAuth flow.(one-time)
3. Bootstrap: Use the frontdoor-url received from your backend.

```javascript
import { useState, useEffect } from 'react';

function LightningOutDemo() {
    const [showLightOut, setShowLightOut] = useState(false);
    const [frontdoorUrl, setFrontdoorUrl] = useState("");

    useEffect(() => {
        fetch('/api/lightningoutsingleaccess')
            .then(async (response) => {
                const frontdoorUri = await response.json();
                setFrontdoorUrl(frontdoorUri.frontdoor_uri);
                setShowLightOut(true);
            })
    }, []);

    return (
        <div>
            <script type="text/javascript" async={true} src="https://mindful-narwhal-6i6s53-dev-ed.my.salesforce.com/lightning/lightning.out.latest/index.iife.prod.js"></script>

            {showLightOut && frontdoorUrl && (
                <div className="lightning-container">
                    <lightning-out-application 
                        app-id="<your app-id here>" 
                        components="c-light-out" 
                        frontdoor-url={frontdoorUrl}>
                    </lightning-out-application>
                    <c-light-out></c-light-out>
                </div>
            )}
        </div>
    );
}

export default LightningOutDemo;
```

```javascript
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import HomePage from "./pages/Home";
import AuthSuccess from "./pages/AuthSuccess";
import ContactList from "./pages/ContactList";
import LightningOutDemo from "./pages/LightningOutDemo";

const router = createBrowserRouter([
  { path: '/', element: <HomePage/> },
  { path: '/token', element: <AuthSuccess/>},
  { path: '/contacts', element: <ContactList/>},
  { path: '/lightningOut', element: <LightningOutDemo/>},
]);

function App() {
  return <RouterProvider router={router}/>;
}

export default App;
```

That's it! The UI mashup is done.

---

## Summary of Data Flow

1. Handshake: Frontend calls Backend → Backend redirects to Salesforce for login.
2. Token Exchange: Salesforce sends code to Frontend → Frontend sends code to Backend → Backend gets and stores tokens.
3. Session Setup: Backend calls Salesforce with access_token to get frontdoor_uri.
4. Rendering: Frontend provides frontdoor_uri to the tag, which initializes the secure session and renders your LWC.

---

# Tips for Enhanced Security

## Enhanced Policy: Secure Integration with Least Privilege

To maximize security when using Lightning Out 2.0, you should move away from standard user profiles. Instead, configure your External Client App (ECA) to use a dedicated integration user. This limits the "blast radius" if a session URL is ever intercepted.

### 1\. Configure the "Least Privilege" User

Instead of using a standard administrator or guest profile, create a dedicated Integration User:

- Profile: Assign the Minimum Access - API Only Integrations profile.
- Security Benefit: This prevents the user from ever logging into the Salesforce UI (browser-based login). Even if a malicious actor captures the frontdoor-url, they cannot navigate to Salesforce Setup, Records, or Apps outside of what the LWC specifically exposes.
- Permission Sets: Create a Permission Set that grants only the specific Object, Field, and Apex Class access required for your LWC to function. Assign this to your Integration User.

### 2\. Policies: Admin Approved Users

In your ECA settings, set Permitted Users to Admin approved users are pre-authorized.

- Why? This bypasses the "Allow/Deny" authorization prompt for the user.
- Implementation: After saving the ECA, go to Manage App Policies, and under the Profiles or Permission Sets related list, add the specific Profile/Permission Set created in the step above. This "pre-approves" the integration user for the app.

---

# Conclusion

This walkthrough demonstrates how OAuth 2.0 can be extended beyond standard web apps to secure specialized integration scenarios like **Lightning Out 2.0**, bridging external UI frameworks with Salesforce securely.

Stay tuned for the next post in our OAuth series, where we will dive into the **client-server flow** and explore how to connect **VS Code to Salesforce**!

Full disclosure: this next one is purely for fun since VS Code can already connect to Salesforce using the web-server flow—but we're doing it anyway just because we can!

See you then!
