Restrict access to Amplify hosted App URL(Production environment URL) and allow only via Cognito Hosted UI URL

0

I have hosted a React Application on AWS Amplify. And I am using Cognito User Pool to allow only authenticated users(federated with Azure AD) to access my Amplify app by providing users the Cognito Hosted UI URL(in cognito Call back URL = Amplify App URL) , its working fine my AD users are able to authenticate and access the Amplify App. But the problem is still users can directly access (without authentication) if they access it via Amplify URL which is I want to block, how to do this?

How to restrict AWS Amplify hosted App to be accessed only via Cognito Hosted UI and not with the direct Amplify App URL (Production environment URL) ?

1 Answer
1
Accepted Answer

You should handle this at the application level using Amazon Cognito's authentication mechanisms. What you want to achieve is commonly called "Route Guarding", and it can be done easily in a React app with React Router and AWS Amplify's Auth module.

The idea is to create a higher-order component (HOC) that wraps your protected routes and checks for authentication. If the user isn't authenticated, they're redirected to your Cognito Hosted UI for login.

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { Auth } from 'aws-amplify';

const ProtectedRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      Auth.currentAuthenticatedUser() // if the user is authenticated, render the component, otherwise redirect to Cognito Hosted UI.
        .then(user => <Component {...props} />)
        .catch(err => <Redirect to="YOUR_COGNITO_HOSTED_UI_URL" />) 
    }
  />
);

Then you can use this ProtectedRoute component instead of the regular Route for your protected routes:

<ProtectedRoute path="/protected" component={ProtectedComponent} />

This way, when someone tries to directly access a protected route, they'll be redirected to the Cognito Hosted UI for authentication.

Keep in mind that this doesn't prevent someone from directly loading static assets from the Amplify hosting URL, but it does protect your app's routes and the data within them.

Please replace "YOUR_COGNITO_HOSTED_UI_URL" with your Cognito Hosted UI URL. You should also handle the redirect back from Cognito to your app correctly to ensure a smooth login flow.

This approach assumes you have aws-amplify and react-router-dom installed in your React project. If not, you can add them with npm:

npm install aws-amplify react-router-dom

profile picture
EXPERT
answered a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions