Hey! I'm new to supertokens and I keep running into issues, I'm trying to integrate supertokens into...
n
Hey! I'm new to supertokens and I keep running into issues, I'm trying to integrate supertokens into a angular app using https://app.swaggerhub.com/apis/supertokens/FDI/1.13.0 and https://supertokens.com/blog/adding-social-login-to-your-website-with-supertokens. And I get my callback and the code from github, and when i make the final
/signinup
it fails with:
Copy code
error: "Request failed with status code 401"
status: "FIELD_ERROR"
My code:
Copy code
js
const code = parseCodeFromUrl();
const provider = 'github';
const environment = {
    currentAddress: "http://localhost.com" //<- dev server address
};
const response = await this.axiosInstance.post(
      '/auth/signinup',
      {
        code,
        redirectURI: `${environment.currentAddress}/callback/${provider}`,
        thirdPartyId: provider,
      },
      {
        headers: {
          'rid': 'thirdpartyemailpassword'
        }
      }
    );
r
Hey! I'm new to supertokens and I keep running into issues, I'm trying to integrate supertokens into a angular app using https://app.swaggerhub.com/apis/supertokens/FDI/1.13.0 and https://supertokens.com/blog/adding-social-login-to-your-website-with-supertokens. And I get my callback and the code from github, and when i make the final
/signinup
it fails with:
Copy code
error: "Request failed with status code 401"
status: "FIELD_ERROR"
My code:
Copy code
js
const code = parseCodeFromUrl();
const provider = 'github';
const environment = {
    currentAddress: "http://localhost.com" //<- dev server address
};
const response = await this.axiosInstance.post(
      '/auth/signinup',
      {
        code,
        redirectURI: `${environment.currentAddress}/callback/${provider}`,
        thirdPartyId: provider,
      },
      {
        headers: {
          'rid': 'thirdpartyemailpassword'
        }
      }
    );
Can i see the backend config?
n
Yes,
Copy code
ts
supertokens.init({
    framework: 'fastify',
    supertokens: {
        //FIXME try.supertokens.com is for demo purposes. Replace this with the address of your core instance (sign up on supertokens.com), or self host a core.
        connectionURI: 'https://try.supertokens.com',
        // apiKey: "IF YOU HAVE AN API KEY FOR THE CORE, ADD IT HERE",
    },
    appInfo: {
        appName: 'TrainNet',
        apiDomain: process.env['NODE_ENV'] === 'production' ? 'https://api.trainnet.novy.software' : 'http://api.localhost.com',
        websiteDomain: process.env['NODE_ENV'] === 'production' ? 'https://trainnet.novy.software' : 'http://localhost.com',
        apiBasePath: '/auth',
        websiteBasePath: '/auth'
    },
    recipeList: [
        ThirdPartyEmailPassword.init({
            providers: [
                //FIXME We have provided you with development keys which you can use for testsing.
                Github({
                    clientId: '467101b197249757c71f',
                    clientSecret: 'e97051221f4b6426e8fe8d51486396703012f5bd'
                }),
            ]
        }),
        Session.init() // initializes session features
    ]
});

import { plugin as supertokensPlugin, errorHandler as supertokensErrHandler } from 'supertokens-node/framework/fastify';
fastify.register(supertokensPlugin);
fastify.setErrorHandler(supertokensErrHandler());
r
Can you try something like this and see what the error output is:
Copy code
js
let github = ThirdPartyEmailPassword.Github({
    clientId: "",
    clientSecret: "",
});
ThirdPartyEmailPassword.init({
    providers: [
        {
            ...github,
            get: function (redirectURI: string | undefined, authCodeFromRequest: string | undefined, userContext: any) {
                let getResult = github.get(redirectURI, authCodeFromRequest, userContext);
                return {
                    ...getResult,                    
                    getProfileInfo: async function (authCodeResponse: any, userContext: any) {
                        try {
                            return getResult.getProfileInfo(authCodeResponse, userContext);
                        } catch (err) {
                            console.log(err);
                            throw err;
                        }
                    }
                }
            }

        },
    ],
});
n
Yes, give me a sec
Should I leave the clientId and secret field empty?
r
no. Use your values
Can you show me what the output is of the console.log in the above code
n
Maybe I'm doing something wrong, but there is none
Copy code
<anonymous>] 127.0.0.1 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36: OPTIONS /auth/authorisationurl?thirdPartyId=github - 200  
2022-04-13 15:48:53.842  INFO  [apps/trainnet-backend/src/index.ts:16 Object.<anonymous>] 127.0.0.1 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36: GET /auth/authorisationurl?thirdPartyId=github - 200  
2022-04-13 15:48:57.309  INFO  [apps/trainnet-backend/src/index.ts:16 Object.<anonymous>] 127.0.0.1 Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.88 Safari/537.36: POST /auth/signinup - 200
r
Can you enable debug logs and show me the out of that when you are making the API call?
There should be a troubleshooting section in our docs that has instructions on how to enable debug logs
So it did send a 200 response. As per the logs.
n
Yes, it sends a 200, but the content is a field_error
r
oh right yea.
I think the issue might be that the redirecURI that you are passing should be
${environment.currentAddress}/auth/callback/${provider}
you are missing the /auth/ part
n
Oh, yes, let me try that
No, it's still the same
r
it's annoying cause the auth providers barely give any info about why the request failed. It's just "request failed with status code 401"
what's the callback url that you configured on github?
n
r
are you providing the scope array yourself on the backend?
n
No,
Copy code
ts
export class SupertokensService {
  public axiosInstance: AxiosInstance;

  constructor() {
    SuperTokens.init({
      apiDomain: environment.apiServerAddress,
      apiBasePath: '/auth',
    });

    this.axiosInstance = axios.create({
      baseURL: environment.apiServerAddress,
      timeout: 10000,
    });
    SuperTokens.addAxiosInterceptors(this.axiosInstance);
  }

  public async thirdPartyRedirect(provider: string) {
    const intialResponse = await this.axiosInstance.request({
      url: `/auth/authorisationurl?thirdPartyId=${provider}`,
      method: 'GET',
      headers: {
        rid: 'thirdpartyemailpassword'
      }
    });
    if (intialResponse.status !== 200 || intialResponse.data.status !== 'OK') throw new Error('Failed to get auth url');

    const authUrl = intialResponse.data.url;
    const urlObj = new URL(authUrl);

    urlObj.searchParams.append('redirect_uri', `${environment.currentAddress}/auth/callback/${provider}`);

    const url = urlObj.toString();
    window.location.href = url;
  }

  public async login(provider: string, code: string) {
    const response = await this.axiosInstance.post(
      '/auth/signinup',
      {
        code,
        redirectURI: `${environment.currentAddress}/auth/callback/${provider}`,
        thirdPartyId: provider,
        authCodeResponse: {
          access_token: 'string',
          id_token: 'string'
        },
      },
      {
        headers: {
          'rid': 'thirdpartyemailpassword'
        }
      }
    );
    console.log(response);
  }
}
r
no i mean on the backend
n
No, there are no scopes
r
Also, you should remove:
Copy code
authCodeResponse: {
          access_token: 'string',
          id_token: 'string'
        },
all you need to give is
code
,
redirectURI
and
thirdPartyId
.
The
authCodeResponse
is for mobile apps flow (authorisation code grant flow via PKCE)
n
Ok, I removed it
r
does it work now?
n
No, but I put some console.logs in the backend
And
Copy code
js
providers: [
                {
                    ...github,
                    get: function (redirectURI: string | undefined, authCodeFromRequest: string | undefined, userContext: any) {
                        const getResult = github.get(redirectURI, authCodeFromRequest, userContext);
                        return {
                            ...getResult,
                            getProfileInfo: async function (authCodeResponse: any, userContext: any) {
                                try {
                                    const result = await getResult.getProfileInfo(authCodeResponse, userContext);
                                    console.log(result); //<- this one has my login details (id, email, verified)
                                    return result;
                                } catch (err) {
                                    console.log(err);
                                    throw err;
                                }
                            }
                        };
                    }
                },
            ],
So getProfileInfo suceeds
r
ok great!
so the output of the API is fine?
n
The client still receives a 401 response...
r
Now can you remove all the code that i gave on the backend and add the original backend code back?
that is
Copy code
providers: [
                //FIXME We have provided you with development keys which you can use for testsing.
                Github({
                    clientId: '467101b197249757c71f',
                    clientSecret: 'e97051221f4b6426e8fe8d51486396703012f5bd'
                }),
            ]
n
Yes, give me a second
The app is proxied through nginx and it returns an 502 saying that upstream returned malformed response... Which is kind of strange, but let me investigate
r
Huh.. maybe you have a limit on the size of the headers that are allowed to be sent back?
The cookies attached to the response can be lengthy.
n
Yeah, it was more than 1kb 🤣 But it works now, and it was definitely that missing
/auth
Thank you so much for your help
r
hehe. no worries 🙂
n
It would have taken an eternity to figure it out on my own
r
well.. we are working on a vanilla JS SDK which will expose help functions instead of you having to make the API calls yourself. That would have really helped in this case.
n
Well, I'm looking forward to it 🙂