frontend-auth

frontend-auth simplifies the process of making authenticated API requests to backend edX services by providing common authN/authZ client code that enables the login/logout flow and handles ensuring the presence of a valid JWT cookie.
Usage
To install frontend-auth into your project:
npm i --save @edx/frontend-auth
frontend-auth
uses axios interceptors to ensure that a valid JWT cookie exists in your user's browser before making any API requests. If a valid JWT cookie does not exist, it will attempt to obtain a new valid JWT cookie using a refresh token if one exists in cookies. If a refresh token does not exist or the refresh token is not valid the user will be logged out and redirected to a page of your choosing. Instead of referencing axios directly, you should obtain an http client by calling the getAuthenticatedAPIClient
function provided by frontend-auth
:
import { getAuthenticatedAPIClient } from '@edx/frontend-auth';
const apiClient = getAuthenticatedAPIClient({
appBaseUrl: process.env.BASE_URL,
loginUrl: process.env.LOGIN_URL,
logoutUrl: process.env.LOGOUT_URL,
refreshAccessTokenEndpoint: process.env.REFRESH_ACCESS_TOKEN_ENDPOINT,
accessTokenCookieName: process.env.ACCESS_TOKEN_COOKIE_NAME,
userInfoCookieName: process.env.USER_INFO_COOKIE_NAME,
});
frontend-auth
provides a PrivateRoute
component which can be used along with react-router
to require authentication for specific routes in your app. Here is an example of defining a route that requires authentication:
<ConnectedRouter history={history}>
<Switch>
<Route exact path="/unauthenticated" component={UnauthenticatedComponent} />
<PrivateRoute
path="/authenticated"
component={AuthenticatedComponent}
authenticatedAPIClient={apiClient}
redirect={process.env.BASE_URL} // This should be the base URL of your app.
/>
</Switch>
</ConnectedRouter>
frontend-auth
also provides Redux actions and a reducer for injecting user profile data into your store.