Passport Auth Strategy

default discord avatar
thefrontendlast year
17

I am reading some posts and the documentation and was wondering if I can use passport strategies to build something like this:



1.) I have an admins collection with access to the dashboard and default email/password auth


2.) I have a users collection with NO access to the dashboard but access to the database after login via


- default email/password auth


- passport apple auth


- passport google auth



I just added passport-apple for the users collection and every time I start payload and visit the dashboard-login page I get redirected to the apple auth page. I‘m not sure why this is happening as this collection is not even meant to login to the dashboard. 🤔



EDIT

Currently the code looks like this.



collections/Users.ts


import { CollectionConfig } from 'payload/types';
import { isLoggedIn } from '../access/isLoggedIn';
import { verifyEmail } from '../emails/verifyEmail';
import { forgotPassword } from '../emails/forgotPassword';
import AppleStrategy from '../auth/apple';

// import passport from "passport";
const Users: CollectionConfig = {
  slug: 'users',
  auth: {
    cookies: {
      sameSite: 'none',
      secure: true,
    },
    strategies: [
      {
        name: 'apple',
        strategy: AppleStrategy
      },
    ],
    verify: {
      generateEmailHTML: verifyEmail,
    },
    forgotPassword: {
      generateEmailHTML: forgotPassword,
    }
  },
  admin: {
    useAsTitle: 'email',
  },
  access: {
    create: () => true,
    read: isLoggedIn,
  },
  fields: [
    
  ],
}

export default Users;


auth/apple.ts


import Strategy from "passport-apple";

const AppleStrategy = new Strategy(
  {
    clientID: "XXX",
    teamID: "XXX",
    callbackURL: "XXX",
    keyID: "XXX",
    privateKeyLocation: "XXX",
    passReqToCallback: true
  },
  function(req, accessToken, refreshToken, idToken, profile, cb) {
    // 
    cb(null, idToken);
}

);

export default AppleStrategy;
  • default discord avatar
    notchrlast year

    @TheFrontend What's the apple auth code look like?

  • default discord avatar
    thefrontendlast year

    I just updated the original post above, there is not much going on. I just copied and configured the blank code from passport js.



    Also my payload config looks like this



    payload.config.ts


    import { buildConfig } from 'payload/config';
    import path from 'path';
    
    import AdminUsers from './collections/AdminUsers';
    import Users from './collections/Users';
    
    const createStripeSubscriptionPath = path.resolve(__dirname, 'auth/apple');
    const mockModulePath = path.resolve(__dirname, 'mocks/emptyObject');
    
    export default buildConfig({
      serverURL: process.env.APP_URL,
      csrf: [
        'https://localhost:5173',
      ],
      admin: {
        user: AdminUsers.slug,
        meta: {
          titleSuffix: '- Demo',
        },
        webpack: (config) => ({
                ...config,
                resolve: {
                    ...config.resolve,
                    alias: {
                        ...config.resolve.alias,
                        [createStripeSubscriptionPath]: mockModulePath,
                    }
                }
            })
      },
      collections: [
        AdminUsers,
        Users,
      ],
      typescript: {
        outputFile: path.resolve(__dirname, 'payload-types.ts'),
      },
      graphQL: {
        disablePlaygroundInProduction: false,
        schemaOutputFile: path.resolve(__dirname, 'generated-schema.graphql'),
      },
    });
  • default discord avatar
    notchrlast year

    Weird, looks OK to me



    and it's redirecting on the login page?



    how so

  • default discord avatar
    thefrontendlast year

    Now I only run into CORS issues on the login page but it's still redirecting when trying to open /api/graphql-playground

    Bildschirmfoto_2023-02-27_um_21.26.46.png
    Bildschirmfoto_2023-02-27_um_21.27.08.png
  • default discord avatar
    notchrlast year

    Hmm that's showing your request is failing though



    Is your allowed origins set on apple dev side?

  • default discord avatar
    thefrontendlast year

    There is nothing I can really set manually. I did enter the domains that are allowed to use sign-in-with-apple



    the exact same happens when I use the passport-google-oauth20 library. Must be missing something here 🤨



    @jmikrut any ideas on this? I also noticed once I add multiple strategies it always tries to redirect me to the one at the end of the array. When I try to open the graphql-playground or any api route it always redirects me to the external auth page (google in this case)

  • discord user avatar
    jmikrut
    last year

    So this is a problem with many Passport SSO plugins



    they are built to redirect

    all

    routes that they "protect" to the SSO auth page (in this case, apple). Even API routes. So when you load the dashboard, and the dashboard makes requests to /api/users/init, and /api/users/me, etc etc - -

    those

    requests are actually also incorrectly being redirected to your SSO login page... and showing CORS errors that result from Apple / Google / wherever



    that's the tough part with SSO. 99% of the existing plugins out there are meant to redirect

    all

    routes if you are not authenticated, when really, you only want to redirect anything on /admin, and leave the /api routes alone. API routes should remain left as-is, because it should be possible to hit those routes without being authenticated



    there are different "strategy" methods out there - some are "bearer strategies" - and this is what you want. Basically, leave it up to the user to either auth or not auth, via header or cookie or similar. If no cookie / header / etc is found, they are simply not authenticated and the route proceeds as normal.



    but TL;DR, your CORS error is a red herring and is not the real issue here. What's really happening is that those requests are incorrectly being redirected

  • default discord avatar
    supaku8 months ago

    @TheFrontend Did you end up finding a path forward here? I've also set up

    passport-google-oauth20

    as well and have arrived where you did. I previously got the payload oauth plugin(

    https://github.com/thgh/payload-plugin-oauth/blob/main/src/index.ts

    ) to work, but wanted to be able to add multiple strategies and found myself on this path.

  • default discord avatar
    rickbyontlabs8 months ago

    yeah, same thing here

  • default discord avatar
    wizen33808 months ago

    Do you guys have any working example on how to authenticate via google oauth on payload?

  • default discord avatar
    rickbyontlabs8 months ago

    This thread gave me some additional insights in other ways to implement authentication, haven't gotten to google auth yet but I can login with my own endpoint by getting the user from the database, creating a jwt token and setting it in the payload cookie.


    https://discord.com/channels/967097582721572934/1073356002101035108

    The thread says to disable localAuthStrategy though, which I haven't needed to do. I wonder why that is..


    Perhaps im still to run into that limitation as I work on integrating googleAuth in this endpoint

  • default discord avatar
    wizen33808 months ago

    I don't think that would be possible via auth.strategies - I think you need to create a separate express endpoint, get user via payload context, create a jwt token and set it to payload cookie

  • default discord avatar
    rickbyontlabs8 months ago

    @Wizen Yep, thats exactly how I did it

  • default discord avatar
    thefrontend5 months ago

    @Supaku @Rick | Byont Labs @Wizen I just started refactoring my plugin and can share a repo within the next week. It's basically a fork of thgh's plugin but also enables different strategies (e.g. Apple).

  • default discord avatar
    rickbyontlabs5 months ago

    Cool! We've already got something that works RN and are crammed as we're nearing product launch so can't migrate for the moment.


    Keep me updated though, would love to see what you've made later. Who knows in the

  • default discord avatar
    lakshxy_5 months ago

    @TheFrontend Are there any updates? Would like to see if you can share the repo

  • default discord avatar
    thefrontend4 months ago

    Yes,



    I just created a simple repo here:



    https://github.com/JulianAtTheFrontend/payload-plugin-sso

    The documentation right is very minimal but I added a lot of comments inside the code. Will update this within the next weeks.



    Let me know if anything is unclear!

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.