Protecting specific app areas
Overview
Control who sees what in your application. For instance, check whether a user is logged in or not and redirect unauthorized visitors to the login page. If a user is logged in, you can control what information they have access to based on their role. Read below to learn more.
React ONLY
This feature is currently available for React components only.
Redirect Visitors to Login
Redirect visitors to the login page when they are not logged in.
Here is sample code:
import { useAuthUser } from "@frontegg/react";
function App() {
// This will redirect to login in case we are not logged in
const user = useAuthUser();
return (
<div className="App">
Logged in as {user?.name}
</div>
);
}
export default App;
The useAuthUser
hook knows how to check whether the user is logged in. If the user is not logged in, the hook redirects them to the login page. In the example above, if the user is logged in, the component displays "Logged in as" plus the user's name instead of redirecting to login.
Display Information Based On Role
Even if a user is logged in, you can control which content they can access based on their role.
Wrap the content you want to protect with the AuthorizedContent
component. That component has a requiredRoles
prop that you pass an array of role names into.
Before showing the user any content, the AuthorizedContent
component checks the user's role against your list of required roles for that content. It only shows the content to users who have a role that appears in your required roles.
import { AuthorizedContent, useAuthUser } from "@frontegg/react";
function App() {
// This will redirect to login in case we are not logged in
const user = useAuthUser();
return (
<div className="App">
Logged in as {user?.name}
<AuthorizedContent requiredRoles={['Admin']} >
<div>
Private area for admins
</div>
</AuthorizedContent>
</div>
);
}
export default App;
Roles and Permissions
Read about managing roles and managing permissions.
Updated 3 months ago