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

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

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")

How to solve Apollo Studio Sanbox Cors?

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.

Django + Angular + Django-allauth

I'm creating a web application using Django as the backend and Angular for the front.
Angular is running on a Yeoman stack on localhost:9000 while Django is running on localhost:8000 and I'm using grunt-contrib-proxy to redirect all the $http calls from angular at /api to the django port. So for example, if Angular asks for localhost:9000/api/hello this will be redirect to localhost:8000/api/helloand django will serve it.
I'm planning to setup Django Rest Framework for serving all the Angular request to the /api path.
So far so good.
Now, I have an already configured and working installation of Django-allauth for making Oauth authentication to third party services. It does work using plain old Django but I have no idea how to make this work in conjunction with Angular.
The only thing that came into mind was serving the allauth views through django rest framework, but what about redirection after authentication? I can't wrap my mind around it.
Is it better to drop this approach and make the Oauth authentication straight from the front (Angular)?
EDIT:
I managed to call the login view from Angular
In grunt-contrib-proxy I've added the account context and rewrite rule:
context: ['/api', '/accounts'],
rewrite: {
'^/api': '/api',
'^/account': '/accounts'
}
I've made an ajax call from angular, asking for the allaluth login view (for example for github): $http.get('/accounts/github/login/?process=login')
The problem is that I get back:
XMLHttpRequest cannot load https://github.com/login/oauth/authorize?scope=&state=BlaBla&redirect…ub%2Flogin%2Fcallback%2F&response_type=code&client_id=BlaBlaBla. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. (index):1
(The BlaBla was added by me). I think I'm doing something totally wrong
You need to add an
Origin: http://localhost:9000
to the header in the request that angular sends to Django.
Also make sure the server running Django returns an
Access-Control-Allow-Origin: *
see here for more information.

EmberJs as a PhoneGap with external API

please can you advise on the following:
I have a web application written in emberjs with Rails as back-end. And now I'm going to port this application with phonegap to iOS, and the thing that I'm struggling is how to set my API endpoint that will be working in iPhone?
As I understand EmberJs when used on the web via browser, uses your current location to issue API requests, but this approach doesn't working when using the application as iOS app.
I'm really looking for some elegant solution to simply replace the host name or something?
Thanks for help!
UPDATE:
This one works for changing the API URL
DS.RESTAdapter.reopen({
url: 'http://somedomain.com'
});
But now, there is access-controll issue:
Origin http://somedomain.com is not allowed by Access-Control-Allow-Origin.
Since you haven't posted any code on how your adapter is configured, this is the right way to set a custom url for your adapter:
DS.RESTAdapter.reopen({
url: 'https://somedomain.com/api'
});
Then if you have a model e.g. App.User, the requests for the list of App.User would now go to https://somedomain.com/api/user/ and for a specific user id to https://somedomain.com/api/user/123 respectively.
Update
When testing from the browser you have to start the browser (assuming chrome) with the flag --disable-web-security to make cross origin work. But in real live you have to configure your server to set the response HTTP HEADERS using:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, ...
So in the case of rails you could do something like this to configure your controllers serverside to accept cross origin requests and set the headers accordingly:
...
after_filter :cors_set_access_control_headers
def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT' # etc. etc.
headers['Access-Control-Max-Age'] = "1728000"
end
...
For more extensive examples on how to configure CORS for rails you could search for "CORS for JSON and Rails" for example.
Hope it helps

How do I authenticate and consume an external api with backbone?

I'm trying to create a very basic little backbone app that displays stats from my company's Harvest account. They have a REST API which authenticates via Basic Auth or oAuth. I seem to be faced with two problems here:
Authentication
Cross-origin requests
So I've started with setting the url for my collection to the respective url:
var Projects = Backbone.Collection.extend({
url: 'https://mycompany.harvestapp.com/projects',
});
And I've tried using this basic auth plugin but I can't tell if that part is working because I'm still getting Access-Control-Allow-Origin errors.
What's the best way to go about this?
This other StackOverflow question is similar and has more details that you should take a look at.
But the general idea is this, if you don't have access to the remote server (which I presume you do not with Harvest) then you need to perform the cross-site requests from your own server that you do control, most likely the one you are deploying this backbone app on. That means writing some server-side code (PHP, Node, etc.) to perform the requests (perfectly legal from server side) and then having your client (Backbone app) request from these scripts.
Here is a brief/pseudo-example with php:
request.php
<?php
echo file_get_contents('https://mycompany.harvestapp.com/projects');
?>
projects.js
var Projects = Backbone.Collection.extend({
url: 'request.php',
});