Reputation: 125
So I have connected auth0 to my backend which consists of Node, Express and a MongoDB database. I am able to create accounts and log in using endpoints of my server (localhost:4000/login) but this is not what I want. I am also building a front-end for my application which will be where users are asked to authenticate and only then are they allowed to access protected routes. I need to find a way to connect my auth0 application (that is already connected to my backend) to my frontend.
I am not sure how to implement this so any help on this would be amazing. If this question has been answered or if a resource exists online that tackles this problem, please point me to it.
Upvotes: 1
Views: 1508
Reputation: 2066
and here help arrived.
Firstly, check this example.
Secondly, here is an idea of how any page in nextjs works with auth0
A. Any page can be secured with auth0. By default your pages are not secured
B. To secure the page you need to:
export const getServerSideProps = withPageAuthRequired({
//returnTo: '/foo',
async getServerSideProps(ctx) {
return { props: { customProp: 'bar' } };
}
});
C. You can also secure API endpoints (but in this case it will not be accessible from anywhere except your client, so you couldn't for example access from postman)
import { withApiAuthRequired, getAccessToken, getSession } from '@auth0/nextjs-auth0';
export default withApiAuthRequired(async function test(req, res) {
try {
const session = getSession(req, res);
} catch (error) {
res.status(error.status || 500).json({
code: error.code,
error: error.message
});
}
});
D. You can also call, for example, getSession
almost everywhere to get info about 'clients' connected.
E. You need to also check this docs, this is quite geeky
F. You can secure a component
also, for example, imagine you created a 'secured' component as SecuredLayout
. Every time you embed your content with SecuredLayout
page will trigger the 'login' page to user logins. (useful for my personal space
for clients). Try always to decompose your elements.
P.S. You need to run your localhost on HTTPS protocol.
Upvotes: 1