# Announcing MCP Authentication: secure your MCP servers with PropelAuth

In this guide, we’ll build an example application in React/Express where users can sign up, login, and manage their accounts. We'll include social logins (Login with Google), passwordless logins, and allow our users to upload their own profile pictures.

We're going to use the following technologies for this blog post:

- [React.js](https://reactjs.org/?ref=propelauth.mymidnight.blog) \- for our frontend
- [Express (Node.js)](https://expressjs.com/?ref=propelauth.mymidnight.blog) \- for our backend
- [PropelAuth](/content/?ref=propelauth.mymidnight.blog) \- for user login and management

The code is available on GitHub in these two repos: [React](https://github.com/PropelAuth/react-propelauth-starter?ref=propelauth.mymidnight.blog) and [Express](https://github.com/PropelAuth/express-propelauth-starter?ref=propelauth.mymidnight.blog).

### Setting up Authentication

PropelAuth fully manages your signup, login, and account management flows. Features like social login (Login with Google), passwordless/magic links, and 2FA for our end users can be enabled in one click. You can sign up [here](https://auth.propelauth.com/signup?ref=propelauth.mymidnight.blog).

The first thing to do after you sign up is create your project:

Afterwards, a test environment is created for you.

Your default login page includes login, signup, account pages, and optional organization management pages. There's a default logo, color scheme, and both [passwordless and password-based](/content/post/react-express-authentication-guide?ref=propelauth.mymidnight.blog) login. You can fully test what your end users will experience, transactional emails included, but you might want to configure its style first in your dashboard under the **Hosted Auth Pages** section.

From here, you can [configure other aspects of your end-users auth experience](https://docs.propelauth.com/getting-started/?ref=propelauth.mymidnight.blog), including:

- Adding "Login in with Google" or other SSO providers
- Collecting additional metadata on signup - like username or first name/last name
- Allowing your users to upload their own profile picture
- Letting your end-users create organizations and invite their coworkers (called B2B support)

After configuring your project, it's now time to integrate it with your frontend and backend.

### Authentication in React

One of the benefits of having PropelAuth manage your users is you can use whatever frontend or backend you want - or even migrate between them. In this case, we'll use React.js.

#### Creating a new React project

If you don't have a project already, you'll want to follow the [official instructions](https://create-react-app.dev/docs/getting-started?ref=propelauth.mymidnight.blog) and run:

```shell
$ npx create-react-app frontend
```

#### Installation

The [@propelauth/react](https://www.npmjs.com/package/@propelauth/react?ref=propelauth.mymidnight.blog) package provides an easy interface to access your users' information and manage auth tokens.

```shell
$ yarn add @propelauth/react
```

#### Setup

At the top of our application, we will add our [**AuthProvider**](https://docs.propelauth.com/reference/frontend-apis/react.html?ref=propelauth.mymidnight.blog#set-up-authprovider)

```jsx
import {AuthProvider} from "@propelauth/react";

ReactDOM.render(
    <AuthProvider authUrl={process.env.REACT_APP_PROPELAUTH_AUTH_URL}>
        <App/>
    </AuthProvider>,
    document.getElementById('root')
);
```

The authUrl is available on the **Frontend Integration** section of your PropelAuth project.

When a user logs in to our hosted pages, a secure, HTTP-only cookie is set. The [**AuthProvider**](https://docs.propelauth.com/reference/frontend-apis/react.html?ref=propelauth.mymidnight.blog#set-up-authprovider) checks if the user is logged in, fetches auth tokens and user information. In production, you must use a custom domain to avoid third-party cookie issues.

#### Usage

[**withAuthInfo**](https://docs.propelauth.com/reference/frontend-apis/react.html?ref=propelauth.mymidnight.blog#withauthinfo) injects user information into your React components. Example:

```jsx
import {withAuthInfo} from '@propelauth/react';

function AuthInfoOnFrontend({user}) {
    return <span>
        <h2>User Info</h2>
        {user && user.pictureUrl && <img src={user.pictureUrl} className="pictureUrl" />}
        <pre>user: {JSON.stringify(user, null, 2)}</pre>
    </span>
}

export default withAuthInfo(AuthInfoOnFrontend);
```

If we add this component to our App and visit our site before logging in, we'll see:

After logging in, we'll see:

In addition to **user**, [**withAuthInfo**](https://docs.propelauth.com/reference/frontend-apis/react.html?ref=propelauth.mymidnight.blog#withauthinfo) also injects **isLoggedIn**, **accessToken**, and **orgHelper**.

#### Creating Login/Logout Buttons

[**@propelauth/react**](https://docs.propelauth.com/reference/frontend-apis/react.html?ref=propelauth.mymidnight.blog) provides React hooks for user redirection to login/signup/account pages. Example:

```jsx
import {withAuthInfo, useLogoutFunction, useRedirectFunctions} from '@propelauth/react';

function AuthenticationButtons({isLoggedIn}) {
    const logoutFn = useLogoutFunction();
    const {redirectToSignupPage, redirectToLoginPage, redirectToAccountPage} = useRedirectFunctions();

if (isLoggedIn) {
        return <div>
            <button onClick={redirectToAccountPage}>Account</button>
            <button onClick={() => logoutFn()}>Logout</button>
        </div>;
    } else {
        return <div>
            <button onClick={redirectToSignupPage}>Signup</button>
            <button onClick={redirectToLoginPage}>Login</button>
        </div>;
    }
}

export default withAuthInfo(AuthenticationButtons);
```

#### Making authenticated requests

To make an **authenticated** request on behalf of your user, provide the access token in the Authorization header:

```text
Authorization: Bearer ACCESS_TOKEN
```

Example using fetch:

```js
function fetchWhoAmI(accessToken) {
    return fetch("/whoami", {
        headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${accessToken}`
        }
    }).then(response => {
        if (response.ok) {
            return response.json();
        } else {
            return {status: response.status};
        }
    });
}
```

You can use [React's useEffect](https://reactjs.org/docs/hooks-effect.html?ref=propelauth.mymidnight.blog) hook for this:

```jsx
import {withAuthInfo} from "@propelauth/react";
import {useEffect, useState} from "react";

function AuthenticatedRequestToBackend({accessToken}) {
    const [response, setResponse] = useState(null);

useEffect(() => {
        fetchWhoAmI(accessToken).then(setResponse);
    }, [accessToken]);

return <span>
        <h2>Server Response</h2>
        <pre>{response ? JSON.stringify(response, null, 2) : "Loading..."}</pre>
    </span>;
}

export default withAuthInfo(AuthenticatedRequestToBackend);
```

#### A quick note on CORS

To fix CORS issues, add the following to your package.json:

```text
"proxy": "http://localhost:3001"
```

### Authentication in Express

#### Creating an unprotected route

First, we install express and dotenv:

```shell
$ mkdir backend
$ cd backend
$ npm init
$ npm install --save express dotenv
```

Then, create the route our frontend expects (/whoami):

```js
require('dotenv').config();
const express = require('express');
const app = express();
const port = 3001;

app.get('/whoami', (req, res) => {
    res.json({'test': 'test'});
});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`);
});
```

#### Protecting our route

Our frontend passes an access token, and now we’ll use PropelAuth’s Express library [@propelauth/express](https://docs.propelauth.com/reference/backend-apis/express.html?ref=propelauth.mymidnight.blog) to validate the user:

```shell
$ npm install --save @propelauth/express
```

Protecting the API:

```js
// New file: propelauth.js
const propelAuth = require('@propelauth/express');

module.exports = propelAuth.initAuth({
    authUrl: process.env.PROPELAUTH_AUTH_URL,
    apiKey: process.env.PROPELAUTH_API_KEY,
});
```

```js
// back in index.js
const {requireUser} = require('./propelauth');
app.get('/whoami', requireUser, (req, res) => {
    res.json({userId: req.user.userId});
});
```

### Wrapping up

In under 100 lines of code, we built an advanced application with PropelAuth taking care of authentication. We’ve made authenticated requests from frontend to backend, identifying users based on their requests.
