Passing Access Token from an api to different pages - reactjs

So I'm currently using the Spotify API with reactJS and get the access token of a user when the login is authenticated by Spotify, it redirects to the first page that I set it to, ('/') of Component={Home}. But from that Home page, I want to route to a different page with the path '/playlist' onClick of a button in which I push the url by,
this.props.history.push('/playlist/#access_tokens=' + spotifyApi.getAccessTokens())
This is the only way I got it to be with the access token passing in the URL.
Is this bad practice?

it's hard to understand your goals for me, but if you want to pass access_token only by url, you can use state to hide token from the user
this.props.history.push({
pathname: '/playlist',
state: {
accessTokens: spotifyApi.getAccessTokens()
}
})
and then get it by the next way
const location = useLocation();
const tokens = location.state && location.state.accessTokens;
But i can't understand why do not you pass your token to any management library like redux, mobx or some other browser storage (localStorage, sessionStorage)?

Related

How to properly save sensitive data on frontend using next.js?

I'm building a web app that has role permissions based, admin, user and also products, product A, B, C, etc. I get these data from a backend api.
Currently, I'm using local storage and useContext hook to save and manipulate these data, but an user that knows it, can easily change this information and manipulate the front end, so I'm wondering now which approach I can use here.
My wish (if it's possible) is to get these information by backend after the login, and reuse the data freely in other components, just importing it, like an useContext hook.
I know that there is Redux, but since I'm using next.js, from what I saw, every rendering it will lose/refresh data, so it won't be usefull here.
I'm also using SWR, so, I tried to get these data from cache.get('key'), but the SWR call must be on the same component to get the data properly from the key cached. It's not working if a call the SWR on the e.g home page, and try to get it in other generic component.
What do you people suggest to go here?
Thanks!
I think you should authenticate your user, then store their access key and identifier in localStorage and global state.
When users access an authorization required page.
You'll check for the access token if it doesn't exist on both global state and localStorage. Redirect (or alert) the authorization error.
If there is an access token. Then send a request to the server with that access token. The server will be in charge of authorizing progress. And you will handle the logic on the front end based on the response from the server.
The thing is the authorization (checking permission for instance) should be done in the backend, not on the frontend
I don't know whether you can manipulate the implementation of the backend API or not. Hope it helps
Following the answers, I created a useContext to use in any component that I need.
Here is what I have in my context:
const [userRoles, setUserRoles] = useState<string[] | undefined>([])
const getUsersRoles = useCallback(async () => {
const getUserRoles = await UsersService.getUsersRoles(userInfo.idUsuario)
setUserRoles(getUserRoles.data)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
Note: UsersService.getUsersRoles function is integration with the API
And how I use it in the component I need:
const { userRoles, getUsersRoles } = useAuth()
if (userRoles?.length === 0) {
getUsersRoles()
return <LoadingGIf tip="Carregando opções..." />
}
With this, I have the data I need here userRoles. And IF the user reload/refresh the page, getUsersRoles is requested and set the data to the userRoles
The downside to this, at least for me, is that I have to add this:
const { userRoles, getUsersRoles } = useAuth()
if (userRoles?.length === 0) {
getUsersRoles()
return <LoadingGIf tip="Carregando opções..." />
}
for every component I need to use the roles data, but I believe that's it. It's working fine and isn't request extra any endpoints of API.
If anyone has a contribuitions or improves to do in the code, fell free to do it.

Handling signin flow in React

I'm trying to implement Last.fm signin in React. After the user logins to Last.fm, they are redirected to
http://localhost:3000/loginlanding/?token=${token id goes here}
How do I capture the url using React Router?
So far, I have tried all these:
path="/loginlanding/?token:id"
path="/loginlanding/:id"
path="/loginlanding/?:id"
None of these seem to work.
Basically, I need to capture the access token and store it in global state.
specify route
<Route path="/loginlanding/:token_id" component={LoginLanding} />
pass token
<Link to=`/loginlanding/${token_id}` />
get token
this.props.match.params.token_id
**you can store your token in the localstorage and access it from there whenever needed.
Or if the token is available in the parent component you can access it as a prop like this.
**
{match:{params:{id}}} //<<<< This can be accessed in the react-router

How to navigate to next page taking params from current page and persist it even after browser refresh in react

I have to navigate to next page on click of a link with parameters from current page and also want to persist that param if browser refresh in reactjs
localStorage is the answer.
before sending the client to the link, transform the data to a json string, then save it on local storage, th
en redirect the client, then get the previous data and parse it.
const data = your-data
const stringData = JSON.stringify(data)
localStorage.set("prevdata", stringData)
Redirect the client, and then
const prevData = JSON.parse(localStorage.get("prevdata"))

Axios default headers cleared after page refresh in React.js

I am setting axios.defaults.headers.Authorization = MY_TOKEN in Login component which is rendered in Authentication component which checks if this.state.loggedin is set to true. If false it renders Login component, if true it renders UserComponent with BrowserRouter.
BrowserRouter reads "/" path and navigates to Documents component. During this navigation page refreshes and axios.defaults.headers.Authorization is cleared returning value of undefined. How can I preserve axios.defaults.headers even if page is refreshed or should I initialize default headers every time router navigates to other component?
UPDATE
Added some code how rendering happens in Authentication.js
render() {
return (
<UserNavigationContainer
{...this.props}
logout={this.onClickLogoutHandler}
/>
);
}
UserNavigationContainer.js renders routs (not complete code)
<BrowserRouter>
<div>
<UserNavigationComponent {...this.props}>
<Switch>
<Route
exact
path="/"
component={UserSubmittedDocumentsContainer}
/>
So actually when UserNavigationContainer gets rendered it navigates to "/" and refreshes page while navigating.
I had a similar experience and here is how I was able to solve it
Persist token to local storage on user login/signup:
the first step was to persist user token to local storage once login/signup succeeds, you can read up on the browser's local storage API here
Move logic that sets Authorization header to a component that always renders regardless of current path (Navigation bar component in my case):
next was to move the logic responsible for setting Authorization header to my Navigation bar component, by doing so, it automatically fetches the active user's token from local storage and sets the authorization header. now regardless of the component being rendered by react-router, authorization header is constantly being set, avoiding the need to do so for every other component.
PS: Moving the logic doesn't stop you from initially setting the authorization header inside the login component, it only solves the problem of doing so for every other component that gets rendered.
I have encountered the same issue. I solved my problem by setting the request common headers in root files. In my case it is index.js.
Do you notice that I am setting app_token from localStorage?
Initially, The AuthLayout renders the login component. If login success I have to redirect to the admin route.
Auth.js
So, I planned to set the headers in the login component. If login success I could able to set app_token in the request headers. All went well until I refresh the page.
Login.js
So, I set the token in localStorage and used it in the index.js to set the headers globally.
Login.js
I guess this is not a better solution. Well, I could able to set the headers globally and get authenticated using the token even after the page refresh.
UPDATE:
Another simple solution for setting authorization in headers is having an interceptor.
Step 1: Create a file called interceptor.js. Create an Instance.
const axios = require("axios");
const axiosApiInstance = axios.create();
// Request interceptor for API calls
axiosApiInstance.interceptors.request.use(
async (config) => {
config.headers = {
Authorization: `Bearer ${localStorage.getItem("token")}`,
};
return config;
},
(error) => {
Promise.reject(error);
}
);
export default axiosApiInstance;
step 2: Call your subsequent API's which require authorization headers as mentioned below.
import axiosApiInstance from "./interceptor";
let response = await axiosApiInstance.get(
"/api/***"
);
return response;
Thanks
Damali's answer is quite correct, but I also think it's worth expanding on this:
Move logic that sets Authorization header to a component that always
renders regardless of current path
To be honest, it's hard to understand much about OP's project structure, because the snippets posted for some reason relate to the auth-routing logic, which isn't the question asked. But, for clarity, elaborating on the above quote:
All authentication logic, including setting the axios header, should be encapsulated in a single component (probably a React Context). It is not as simple as "setting a header and passing go": any production-level app will need to:
Maintain some authentication state (logged in / out?)
Frequently evaluate that state (expired?)
Perhaps maintain and evaluate more detailed login info (eg roles)
Manipulate routing and API requests based on the above
This is the role of an auth module.
The auth module should control the axios authentication header. This means that we are almost certainly talking about two separate modules:
An HTTPs service module (contains and exports the axios instance), and
An auth module
Now: as OP more-or-less observed: if the auth module simply calls the axios instance and applies a header to it upon login, that will not persist after a refresh.
The trouble with Damali's answer is that even if your auth module is always rendered (eg it is at the very top of your app), the axios configuration will nevertheless not persist on page refresh. A page refresh will force a re-render: the header will be gone.
The answer is deceptively simple: re-apply the header every time auth is required (as well as on login). There are many ways to do this, here is just one:
// apiService.js
import Axios from 'axios';
const axios = Axios.create();
export function setDefaultHeader(key, value){
axios.defaults.headers.common[key] = value;
}
export axios;
// auth.js
import { axios, setDefaultHeader } from '../services/apiService.js';
const tokenKey = 'x-auth-token';
setDefaultHeader(tokenKey, localStorage[tokenKey]);
I had a similar problem and my resolve was to use both by retaining my previous model of adding token authorization once the user logs in normally and then doing the same in the index.js file. So, in the index.js file, I added the following:
// in case the page is reloaded, and the person is logged in, keep the authorization header
if (localStorage.getItem('token')) {
axios.defaults.headers.common["Authorization"] = "Token " + localStorage.getItem('token');
}
It first checks if there's a token. Therefore, when a page is reloaded, the axios settings will still remain.

How to wait for information (currentUser) before componentDidMount

I have a user profile page, when I refresh the page my redux store clears and then I have a fetch all the information again from the backend... but my profile page begins to mount before I get that information back.
I this function in my "loggedInRoutes.js". It will get the currentUser from the JWT token I have in localStorage, and save the userName and ID, etc, in my Redux Store
componentDidMount(){
if (localStorage.length===0){
this.props.history.push('/')
}else{
this.props.dispatchCurrentUser()
}
}
It's in the top level of my routes, the switch statement with my route rendering is in the same page.
In my profile page. (I need to check if the currentUser is friends with the user who's profile I went to, that's why I need both infos from the start).
componentDidMount(){
this.props.fetchProfile(this.props.currentUser, this.props.match.params.userId)
this.requestFriendshipFunction()
}
This works if I already have the currentUser in my redux store, but if I do a page refresh while on the profile page, the componentDidMount in the profile page gets called before I have that information, even though I'm calling the "dispatchCurrentUser" in a more container/parent component "loggedInRoutes".
Saving the currentUser info in local storage seems like a bad idea, and I'm not sure where to go from here.
Thank you.

Resources