How could I pass token from cookies to each request using mobx? - reactjs

I'm writing a web application with Next.js and mobx.
How can I pass token (from cookies) for each request to API? Sometimes I should take it from the browser and sometimes from server side (context object).
Notice, that I make requests in mobx actions (#action).
Thanks in advance!

It depends on the way you are calling the API.
You can achieve that with Axios for example:
const token = localStorage.get('access_token');
const { data } = awit axios('/api/users', { headers: { Authorization: `bearer ${token}` } });

Related

React App - Issue with CORS - access to fetch has been blocked by cors policy

I'm making app by using react which is gonna catch data from twitter API
that's my code
import {useEffect, useState, useContext} from 'react'
import {Link, useParams, useNavigate, useLocation} from 'react-router-dom'
export default function Home(){
const [content, setContent] = useState();
const token = 'here is the required token but i cant show you that'
useEffect(() => {
const url = 'https://api.twitter.com/1.1/search/tweets.json?q=something';
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
}
})
.then((response) => {
if(response.status === 404){
console.log('404');
}
else{
console.log(response.status)
console.log('3')
}
})
.then((data) => {
console.log("abba")
console.log(data)
setContent(data)
})
.catch((e) => {
console.log(e.message);
})
}, [])
return(<div>{content}</div>)
}
and i'm getting this type of error
Access to fetch at 'https://api.twitter.com/1.1/search/tweets.json?q=ewron' from origin 'http://localhost:3000' has been blocked by CORS policy:
When I'm catching data by using the same token by using postman everything works fine
I tried to find solution but everyone is refering to backend set on the same machine. How can I solve it in my case ?
A CORS policy is an important feature that prevents other, external websites from accessing an API.
Some APIs have CORS enabled, others have it disabled. And the whitelist will be tailored to the needs/preferences of the developers of that API.
Twitter will, perhaps, allow twitter.com to use Twitter's public api's. Along with other domains they use. Or maybe none at all, idk how their CORS policy is setup. They'll surely have a bit about it in the API docs.
The reason it works for you on postman is that you're not calling it from a website running in your browser, you're calling it from your computer - which is acting as a sort of 'back-end server'. Which is not a CORS policy violation, so it works fine for you.
It's important to note that CORS policies are being enforced by your browser - theoretically, the API has no idea if the request is from a website or a server. Your browser is telling on you, more or less. So it's not a guarantee of security or anything, but it's a pretty decent guard against it.
All of this is to say -- if you want to use their API, you'll want to set up your own routes and have your front-end call on your own backend server/API, and in turn have that call the twitter API. Which is what I'm guessing other people were trying to tell you.

Middleware to verify/update JWT access and refresh tokens

I have an app with JWT authentication written in React/ Django / Django-allauth.
I have an endpoint to verify/ refresh my access token and it works fine. My question is regards to where to put the refresh logic so it is automatically processed before each request? Is there middleware I can use or is there a way to override fetch?
Essentially, I want the app to verify the token, refresh it if necessary, and redirect unauthenticated user to login for every request dependent on JWT authorization. I also don't want to rewrite this logic over and over.
I'm thinking of overriding fetch
async function handle_token() {
const {valid, status} = await API.process_token()
return {
status,
valid,
}
}
// initialize the fetch object to minimize code repeat at every request
// https://stackoverflow.com/questions/44820568/set-default-header-for-every-fetch-request
function updateOptions(options) {
const update = { ...options }
update.headers = Object.assign({
'Content-Type': 'application/json',
'Accept': 'application/json'
}, update.headers ? update.headers : {})
if(update.jwt) {
const token = localStorage.getItem('access') ? localStorage.getItem('access') : ''
update.headers = Object.assign(update.headers, {'Authorization': `Bearer ${token}`})
/*******************************************************************************
* Perhaps put token logic here but unser how to to handle it
********************************************************************************/
const {valid, status} = handle_token()
}
return update;
}
function fetcher(url, options) {
return fetch(url, updateOptions(options));
}
export default fetcher;
Or maybe there is a middleware that is common to use? Thanks

I want a simple authentication with bearer token and rest api which should be stored in local storage and be refresh in given time in REACT

I want a simple authentication with bearer token and rest API which should be stored in local storage and be refreshed in the given time in REACt.
as I know react is a library and tends to do simple work that concerns on Effective UI and Ux. What about HTTPS request stuff and also authentication . I guess Axios should be the fine approach for HTTP request but using third-party library is sick n RWACt especially if you are a beginner who doesn't have a much understanding of promises than react makes you have a nightmare. Any Solution will be great.
Use axios for this purpose. you can use it like this :
axios.post('/login', data)
.then(response => {
localStorage.setItem('token', response.data.token);
});
Also you can use axios interceptors for this purpose. It will run for every request call. for validating and setting headers to requests like this:
const config = {url:'https://...',timeout:10000}
const instance = axios.create({
baseURL: config.url,
timeout: config.timeout
});
instance.interceptors.request.use(
config => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
error => Promise.reject(error)
);

Getting the React CORS preflight error in React Native

I am getting the CORS access error in my React Native app when connecting to an external API.
async componentDidMount() {
// POST request using fetch with async/await
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: JSON.stringify({ type:'accountLookup',storeId:STORE_ID, storeKey:STORE_KEY, memberId:'471324' })
};
const response = await fetch('http://frequent5.revlogical.com/wsMobile', requestOptions);
const data = await response.json();
this.setState({ data: data });
The problem is most likely not with React app, rather with your server which is not configurated to serve your app.
You should set 'Access-Control-Allow-Origin' header on your server to allow your app's address to make requests.
This problem is usually the fault of the backend. Test it with a tool like https://www.test-cors.org/
An alternative is to create a server to be intercepted between the frontend and the API, and you can handle this guy's cors

NextAuth.js signout if Apollo GraphQL token is invalid or it has expired

What would it be the best way to clear the NextAuth.js session when trying to hit the backend (Apollo GraphQL) and it returns a 401 because the token has expired or is invalid?
I thought about an errorLink and signout, but as far as I know signout cannot be used server side at getServerSideProps, but only client-side.
What is the recommended way to do so? Is there any other way to implement a middleware to take care of that scenario?
Thanks
signOut() clears the session by clearing the state in client side , here what you can do is to check from backend if the state exists and if it is not then do something instead of 401(Unauthorized).
Hope You Read It: https://next-auth.js.org/getting-started/client#signout
It depends on which version of Apollo you are using, but assuming you are using Apollo 3.0 <= you can create a setcontext for your requests.
import { setContext } from '#apollo/client/link/context';
const authLink = setContext((_, { headers }) => {
const token = session?.accessToken ? session.accessToken : ""
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
}
});
function createApolloClient(session) {
return new ApolloClient({
cache: new InMemoryCache(),
ssrMode: typeof window === 'undefined',
link: from([
authLink,
errorLink,
createUploadLink({
uri: GRAPHQL_URI,
credentials: 'same-origin'
}),
]),
});
}
Since signOut() rerenders your app you can check the context to see whether it has a valid token on the request from your server. Haven't tested this, but in theory this is how I might implement it.

Resources