How to solve Apollo Studio Sanbox Cors? - apollo

I can't use apollo Studio. After migration for Graphql playground. When I try to run in localhost and redirect me to apollo studio sanbox https://studio.apollographql.com/sandbox?endpoint=http%3A%2F%2Flocalhost%3A5018%2Fgraphql: Unable to connect to localhost.
Please help to solve this

Add CORS configuration options for the server's CORS behavior.
const server = new ApolloServer({
cors: {
"origin": "https://studio.apollographql.com",
"credentials": true
},
typeDefs,
resolvers,
});

Update
I was able to solve my problem. I had added the helmet middleware to Express and just needed to update the contentSecurityPolicy setting.
export default async (app: express.Application) => {
app.use(config.graphqlPath, express.json());
app.use(cors());
app.use(
helmet({
contentSecurityPolicy:
process.env.NODE_ENV === 'production' ? undefined : false
})
);
};
Not sure if that helps since there were not a lot of details on the environment in the original post, but maybe this can help someone else in the future.
Original Post
I'm having the same issue only with Apollo Sandbox. I just get a page stating that I appear to be offline. I checked the console and there are a number of CORS errors.
I also attempted to switch to the GraphQL Playground as a plugin. It displayed the initial loading screen, but never progressed past that point. I checked the console and also saw similar CORS errors.
I'm using apollo-server-express. I've created Apollo servers in the past and have never run into this while trying to run tools locally.

Apollo now supports an embedded version of the Apollo Sandbox & Apollo Explorer that you can host on your Apollo Server endpoint urls. This will remove the need to whitelist the Apollo Studio endpoint in your CORS configuration to use our Explorer. You can use the Explorer right on your server endpoint.
For local development endpoints, pass embed: true to the ApolloServerPluginLandingPageLocalDefault plugin in your Apollo Server config. See more details here.
For production endpoints, pass a graphRef and embed: true to the ApolloServerPluginLandingPageProductionDefault plugin in your Apollo Server config. See more details here.

Related

Problems with AWS Amplify, Next.js and authenticated SSR

I've got a Next.js application that uses AWS Cognito userpools for authentication. I have a custom UI and am using the aws-amplify package directly invoking signIn/signOut/etc... in my code. (I previously used the AWS Hosted UI and had the same problem set out below - I hoped switching and digging into the actual APIs who reveal my problem but it hasn't)
Everything in development (running on localhost) is working correctly - I'm able to login and get access to my current session both in a page's render function using
import { Auth } from 'aws-amplify';
...
export default const MyPage = (props) => {
useEffect(async () => {
const session = await Auth.currentSession();
...
}
...
}
and during SSR
import { withSSRContext } from 'aws-amplify';
...
export async function getServerSideProps(context) {
...
const SSR = withSSRContext(context);
const session = await SSR.Auth.currentSession();
...
}
However, when I deploy to AWS Amplify where I run my staging environment, the call to get the current session during SSR fails. This results in the page rendering as if the user is not logged in then switching when the client is able to determine that the user is in fact logged in.
Current Hypothesis - missing cookies(??):
I've checked that during the login process that the AWS cookies are being set correctly in the browser. I've also checked and devtools tells me the cookies are correctly being sent to the server with the request.
However, if I log out context.req.headers inside getServerSideProps in my staging environment, the cookie header is missing (whereas in my dev environment it appears correctly). If this is true, this would explain what I'm seeing as getServerSideProps isn't seeing my auth tokens, etc... but I can't see why the cookie headers would be stripped?
Has anyone seen anything like this before? Is this even possible? If so, why would this happen? I assume I'm missing something, e.g. config related, but I feel like I've followed the docs pretty closely - my current conf looks like this
Amplify.configure({
Auth: {...}
ssr: true
});
Next.js version is 11.1.2 (latest)
Any help very much appreciated!
You have to use Next#11.0.0 to use getServerSideProps, withSSRContext and Auth module in production.
I had same issue.
My solution was that disconnect a branch has an authentication problem once and reconnect the branch.
What are your build settings? I guess you are using next build && next export in which case this getServerSideProps shall not work. See https://nextjs.org/docs/advanced-features/static-html-export#unsupported-features
To use SSR with AWS amplify see https://docs.aws.amazon.com/amplify/latest/userguide/server-side-rendering-amplify.html#redeploy-ssg-to-ssr or consider deploying on a node server that is actually a server that you can start with next start like AWS EC2 or deploy on Vercel.
Otherwise if you use next export have to make do with client side data fetch only with client side updates only and cannot use dynamic server side features of nextjs.
One reason for context.req.headers not having any cookie in it is because CloudFront distribution is not forwarding any cookies.
This “CloudFront Behaviour” can be changed in two ways:
Forward all cookies, OR
Forward specified cookies (i.e. array of cookie names)
To change the behaviour, navigate to CloudFront on AWS console > Distributions > your_distribution > Behaviors Tab.
Then Edit existing or Create new behaviour > Change cookies settings (for example set it to "All")

My Flutter frontend on FlutLab does not see my Django backend on Repl.it

I am trying (unsuccessfully) to get data from my django backend, developed on repl.it, to my flutter frontend, developed on FlutLab. On Flutter side, I get data successfully from, for example, https://jsonplaceholder.typicode.com/users. On Django side, I render my data normally and get data by Postman, also without problem.
But if my frontend send get() request directly to backend, I see just my circular indicator.
My URL on Flutter/Dio looks like
Response response = await Dio().get("https://djangobackend.myaccountname.repl.co/");
My ALLOWED_HOSTS on Django looks like
ALLOWED_HOSTS = ['djangobackend.myaccountname.repl.co', '0.0.0.0:3000', 'localhost', '127.0.0.1']
My browser is Chrome. My backend and frontend run on the same device (PC).
Actually I have no idea which host I need to use in this case, so, I just added all I could think of.
Is it possible to get data from my backend to frontend in this case and how to do it if yes?
If I need another IDE, please let me know. The limitation is: I can use online IDE only.
I also can provide more details if necessary.
All ideas are highly appreciated!
UPD: This is because of CORS policy, as you can see on attached screenshot.
Your problem is probably related to CORS policy. To check it, please, open Dev Tools => Console on your browser. Probably you need to add 'api.flutlab.io' and 'flutlab.io' to the "Access-Control-Allow-Origin" header on the server-side. If you need some more help, please attach screen or text of errors from the console mentioned above.

Why am I getting "Indicate whether to send a cookie in a cross-site request by specifying its SameSite attribute"?

In a Chrome warning, it says:
Specify SameSite=None and Secure if the cookie should be sent in cross-site requests. This enables third-party use.
How do I do this correctly using express-session?
app.use(
cors({
credentials: true,
origin: ["http://localhost:3000", "https://elated-jackson-28b73e.netlify.app"] //Swap this with the client url
})
);
var sess = {
secret: 'keyboard cat',
cookie: {}
}
if (app.get('env') === 'production') {
app.set('trust proxy', 1) // trust first proxy
sess.cookie.secure = true // serve secure cookies
sess.cookie.sameSite = 'none'
}
app.use(session(sess))
you are getting this because you are using a resource from another site and that server is attempting to set a "cookie" but, it does not have the SameSite attribute set, which is being reported in newer versions of browsers.
this (may) also be shown if you are trying to access the server page from local computer (xampp), which generally doesn't has SSL installed;
set the header line in your server page (if in PHP) as below:
header("Set-Cookie: cross-site-cookie=whatever; SameSite=None; Secure");
(remember: this must be solved from the server side.)
i got the same issue when run my code in localhost. The affected resource is _ga, _gid, _utma, _utmz. All of them from unpkg.com
and i got marker image leaflet failed request but doesnt affect the page.
since i dont understand what the specific problem so i just delete the affected resource cookies in inspect element and the code will run without notif again.
thought i know if it's better to not answer based by personal experience. just tell me if it's not help at all.
If you are using Google login button or any other identity service add this:
<GoogleLogin onSuccess={() =>()} onError={() => ()} cookiePolicy='single-host-origin'/>

How to get cookies working with Nuxt Apollo and SSR correctly?

We've built a framework around Nuxt to get it to work with WordPress really well. We have been pulling our hair out trying to get post previewing working.
A common setup will be a WordPress install running on a domain like http://api.example.com and then to have Nuxt running on http://www.example.com. There is a WordPress plugin called WP-Graph-QL that creates a GraphQL endpoint like http://api.example.com/graphql, and we wrote a CORS plugin to set the correct CORS headers to work with whatever the frontend origin may be. This is that plugin if you are curious https://github.com/funkhaus/wp-graphql-cors
Our Nuxt Apollo setup is this:
export default function() {
return {
httpEndpoint: process.env.DEFAULT_ENDPOINT,
getAuth: () => process.env.BASIC_API_TOKEN || "",
httpLinkOptions: {
credentials: "include"
}
}
}
FYI sometimes the API will be hidden behind a Basic Auth UN/PW (like when on a staging site for example), that is what the getAuth function is doing.
This all seems to work client side, but it fails on SSR for some reason. It seems the cookies don't get sent in the SSR request, but they do in the client side request. Am I missing something super obvious here?
NOTE: I asked this question here 8 days, but am trying here for more attention

React Django REST framework session is not persisting/working

I'm working on a project with Django Rest Framework as back-end and React as front-end. When I set a session variable initially in some function/view and later when I try to access the different view through axios call and in that view if I try to access session variable which i created previously, I get KeyError. Session doesn't seem stored.
I googled I got a similar issue which I'm facing.
Django rest framework Reactjs sessions not working
I followed the process by adding { withCredentials: true } in axios call. Now I'm getting a different error. Now the issue is not able to access the backend. I get an error saying Access to XMLHttpRequest at 'http://127.0.0.1:8000/url/' from origin 'http://localhost:3000' has been blocked by CORS policy
Again I googled the issue which I'm getting and found that I've to add CORS_ORIGIN_WHITELIST in the django settings.py
I followed the below post for that
Django Python rest framework, No 'Access-Control-Allow-Origin' header is present on the requested resource in chrome, works in firefox
I have added CORS_ORIGIN_WHITELIST like this
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000',
'http://127.0.0.1:3000'
]
Still, I'm facing the same issue. I don't know what's going wrong.
Finally after so much of research I found a solution for this.
In the file where we are importing axios to make the call, set the default header below your import
axios.defaults.withCredentials = true;
example:
import axios from "axios";
axios.defaults.withCredentials = true;
axios.get("url")
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error);
});
once this is done go to your settings.py file and add the below configuration
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
so after this if you set a session variable and access it later in any view, you would be able to get the value which you had previously stored.
This solution worked for me. Hopefully if anyone has the same issue, it will work for them too. :)
NOTE
If the session is not storing under localhost:3000 then make sure that you're accessing your front-end application through 127.0.0.1:3000. If you access the front-end application through localhost and if your backend is running on 127.0.0.1 then the session cookie will be set to 127.0.0.1, so changing the front-end URL from localhost:3000 to 127.0.0.1:3000 will solve your problem.
I had a similar issue once. I used firefox as a browser and got the problem solved by installing the CORS everywhere plugin for firefox (https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/). So, if you're using firefox, this might solve your problem.