Hi, I’m starting using Ory Network for an app I’m ...
# general
a
Hi, I’m starting using Ory Network for an app I’m working on. App is currently in heavy development right now. I’ve been able to get OIDC with Google social login working, but then I’m stuck on the ORY session page instead of going back to my app page. I need to get through some issues that seem to be stemming from the tunneling proxy for local development. Likely a simple issue on my end. My setup is similar to the React App integration sample:
Copy code
# In browser
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at <http://localhost:4000/sessions/whoami>. (Reason: CORS request did not succeed). Status code: (null).
Copy code
# In my console
➜  junta-interfaz git:(main) ✗ npx @ory/cli tunnel --dev <http://localhost:3000> --port 4000 --allowed-cors-origins "*" --debug
A browser should have opened for you to complete your login to Ory Network.
If no browser opened, visit the below page to continue:

                <https://project.console.ory.sh/oauth2/auth?audience=https%3A%2F%2Fapi.console.ory.sh&client_id=ory-cli&code_challenge=tl9t-5S9BvTjYNctOUSiGpDm9h6QAo99ec55wqF7Q7E&code_challenge_method=S256&prompt=login+consent&redirect_uri=http%3A%2F%2F127.0.0.1%3A63683%2Fcallback&response_type=code&scope=offline_access+email+profile&state=nTIT60NzhLKVS4DLnblxsz1MKRqb3Otv>
Copy code
# In another console
➜  junta-interfaz git:(main) ✗ npm run dev

> junta-interfaz@0.1.0 dev
> next dev

  ▲ Next.js 14.2.15
  - Local:        <http://localhost:3000>
  - Environments: .env

 ✓ Starting...
 ✓ Ready in 1096ms
m
There is an issue with CORS, you need to make sure that the request and Ory are reachable under the same URL (e.g. localhost:4000) - this is what the tunnel is for - maybe there is some issue with your Ory Tunnel setup? Did you log in to console to complete the Tunnel setup? See here for some debugging tips: https://www.ory.sh/docs/troubleshooting/csrf
a
I did login to the console as well as run
export ORY_SDK_URL=https://<my_project>.<http://projects.oryapis.com|projects.oryapis.com>
I am noticing that in the ory tunnel output it uses 127.0.0.1. Is this an issue?
Copy code
➜  junta-interfaz git:(main) ✗ npx @ory/cli tunnel --dev <http://localhost:3000>
Need to install the following packages:
@ory/cli@1.0.1
Ok to proceed? (y) 

A browser should have opened for you to complete your login to Ory Network.
If no browser opened, visit the below page to continue:

                <https://project.console.ory.sh/oauth2/auth?audience=https%3A%2F%2Fapi.console.ory.sh&client_id=ory-cli&code_challenge=YRvtCRuofxR2F1Aen_YKNc1sEwq0_1M8o59_jri7F6A&code_challenge_method=S256&prompt=login+consent&redirect_uri=http%3A%2F%2F127.0.0.1%3A60081%2Fcallback&response_type=code&scope=offline_access+email+profile&state=qzzqRxH5tSsdWtyE3fEQA4IozCic9DWb>
m
I am noticing that in the ory tunnel output it uses 127.0.0.1. Is this an issue?
Yes it both needs to be on either localhost or 127.0.0.1 - you cant mix them up
a
im not sure how to get the tunnel to work correctly. i am not specifying anywhere to use 127.0.0.1, it just decides that. how to specify or use localhost? my code is now:
npx @ory/cli tunnel <http://localhost:3000> --dev --debug --port 4000
, but
lsof -i :4000
returns nothing
in my conversation with the kapa ai bot, it says that ORY Network does not allow setting
allowed-cors-origins
options from the
@ory/cli tunnel
command as
localhost
as well
m
Can you run me through the exact steps, so I can reproduce this locally? (might not get to it today, pretty busy day already 😬 )
Thanks for sharing! Will see to take a look as soon as I have some time (most likely tomorrow to manage expectations...)
a
If you don’t want to take the risk on the zip file, here’s the important files: src/app/layout.tsx
Copy code
'use client';

import { ReactNode } from 'react';
import '@/styles/globals.css';

interface LayoutProps {
  children: ReactNode;
}

const RootLayout = ({ children }: LayoutProps) => {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  );
};

export default RootLayout;
src/app/page.tsx
Copy code
'use client';

import { useEffect } from 'react';
import { useSessionStore } from '@/stores/sessionStore';
import ory, {basePath, getUserName} from '@/lib/auth/ory';
import { BarChart, LineChart } from '@/components/Charts';

const Home = () => {
  const session = useSessionStore((state) => state.session);
  const setSession = useSessionStore((state) => state.setSession);
  const logoutUrl = useSessionStore((state) => state.logoutUrl);
  const setLogoutUrl = useSessionStore((state) => state.setLogoutUrl);

  useEffect(() => {
    console.log('Checking session');
    ory
      .toSession()
      .then(({ data }) => {
        setSession(data);
        return ory.createBrowserLogoutFlow().then(({ data }) => {
          setLogoutUrl(data.logout_url);
        })
      })
      .catch((err) => {
        console.error(err);
        // Redirect to login page
        window.location.replace(`${basePath}/ui/login`);
      });
  });

  if (!session) {
    return <h1>Loading...</h1>
  }

  const sampleData = [
    { label: 'A', value: 100 },
    { label: 'B', value: 80 },
    { label: 'C', value: 120 },
  ];
  const lineChartData = [
    {
      id: 'Sample Data',
      data: sampleData.map((item) => ({ x: item.label, y: item.value }))
    }
  ];

  return (
    <div>
      <h1>Welcome to Junta
        {
          getUserName(session?.identity)
        }
      </h1>
      <div>
        <h2>Hello, {" "}
          {
            getUserName(session?.identity)
          }
        </h2>
        <BarChart data={sampleData} />
        <LineChart data={lineChartData} />
        <a href={logoutUrl ?? '#'}>Logout</a>
      </div>
    </div>
  );
};

export default Home;
lib/auth/ory.ts
Copy code
import { FrontendApi, Configuration, Identity } from '@ory/client';

export const basePath = process.env.NEXT_PUBLIC_ORY_ENDPOINT || '<http://localhost:4000>';

// Returns either the email or the username depending on the user's Identity Schema
export const getUserName = (identity?: Identity) => identity?.traits.email || identity?.traits.username

export const getEmail = (identity?: Identity) => identity?.traits.email;

const ory = new FrontendApi(
  new Configuration({
    basePath,
    baseOptions: {
      withCredentials: true,
    },
  }),
);

export default ory;
src/components/Charts.tsx
Copy code
'use client';

import { ResponsiveBar } from '@nivo/bar';
import { ResponsiveLine } from '@nivo/line';

interface BarDatum {
  [key: string]: string | number;
  label: string; // The key used as index in the chart
  value: number; // The key used as a data value
}

interface LineDatum {
  id: string;
  data: {
    x: string | number;
    y: number;
  }[];
}

interface BarChartProps {
  data: BarDatum[];
}

interface LineChartProps {
  data: LineDatum[];
}

export const BarChart = ({ data }: BarChartProps) => (
  <div style={{ height: 400 }}>
    <ResponsiveBar
      data={data}
      keys={['value']}
      indexBy="label"
      margin={{ top: 50, right: 50, bottom: 50, left: 60 }}
      padding={0.3}
      colors={{ scheme: 'nivo' }}
      axisBottom={{
        tickSize: 5,
        tickPadding: 5,
        tickRotation: 0,
        legend: 'Label',
        legendPosition: 'middle',
        legendOffset: 32,
      }}
      axisLeft={{
        tickSize: 5,
        tickPadding: 5,
        tickRotation: 0,
        legend: 'Value',
        legendPosition: 'middle',
        legendOffset: -40,
      }}
    />
  </div>
);

export const LineChart = ({ data }: LineChartProps) => (
  <div style={{ height: 400 }}>
    <ResponsiveLine
      data={data}
      margin={{ top: 50, right: 50, bottom: 50, left: 60 }}
      xScale={{ type: 'point' }}
      yScale={{ type: 'linear', min: 'auto', max: 'auto', stacked: true, reverse: false }}
      axisBottom={{
        tickSize: 5,
        tickPadding: 5,
        tickRotation: 0,
        legend: 'Index',
        legendPosition: 'middle',
        legendOffset: 32,
      }}
      axisLeft={{
        tickSize: 5,
        tickPadding: 5,
        tickRotation: 0,
        legend: 'Value',
        legendPosition: 'middle',
        legendOffset: -40,
      }}
    />
  </div>
);
.env
Copy code
#NEXT_PUBLIC_ORY_ENDPOINT="https://<my_project>.projects.oryapis.com" # When using ory network cloud
#NEXT_PUBLIC_ORY_ENDPOINT="<http://localhost:4000>" # When using ory tunnel from @ory/cli
#NEXT_PUBLIC_ORY_API_KEY="ory_pat_..."
src/app/styles/globals.css
Copy code
@tailwind base;
@tailwind components;
@tailwind utilities;

body {
  @apply bg-gray-100 text-gray-900;
  font-family: 'Inter', sans-serif;
}

h1, h2, h3, h4, h5, h6 {
  @apply font-bold;
}

a {
  @apply text-blue-500 hover:underline;
}

button {
  @apply bg-blue-500 text-white font-semibold py-2 px-4 rounded hover:bg-blue-600;
}
@magnificent-energy-493 thank you for any assistance. cors errors seem to get me pretty easily, so i would really appreciate any help
@magnificent-energy-493 Solved? Solution: 1. Seems that once i add the
--project
parameter to the
@ory/cli tunnel
command it works. started giving me better feedback that “no project was specified”. This feedback on the cli command only appeared after I logged in with github 2. I logged in to the ORY Network with my Github instead of my email, even though they both successfully logged me in and allowed me to see the same project IDs and slugs, etc. Not sure if this is related to the solution somehow. I think it may have gone through the sign-up prompt for “give ORY network permissions on your Github profile” type of OAuth popup when I did that. The accounts are connected it seems, not sure if I did that in the past or if it just associated the emails automatically