Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot get any authentication provider to work: redirect_uri_mismatch #6570

Closed
alexdevmotion opened this issue Jun 6, 2020 · 28 comments · Fixed by #7132
Closed

Cannot get any authentication provider to work: redirect_uri_mismatch #6570

alexdevmotion opened this issue Jun 6, 2020 · 28 comments · Fixed by #7132
Assignees
Labels
severity: low If the issue only affects a very niche base of users and an easily implemented workaround can solve source: docs Documentation changes source: plugin:users-permissions Source is plugin/users-permissions package status: confirmed Confirmed by a Strapi Team member or multiple community members

Comments

@alexdevmotion
Copy link

alexdevmotion commented Jun 6, 2020

Describe the bug
I followed the documentation, I tried using the react-login-front-end-app, no matter how hard I try, I always run into the same redirect_uri_mismatch error.

Steps to reproduce the behavior

  1. Select any provider in your strapi admin panel, let's go with GitHub, since it seems to be the simplest and also has a video tutorial from Strapi (tried following it step by step).
  2. Fill in the required fields as described in the docs; also follow the other steps described in the docs
  3. Go to http://localhost:1337/connect/github or click on the Github button inside the React login frontend boilerplate app

Expected behavior
Successful authentication

Screenshots
See in Additional context

System

  • Node.js version: 12.16.1
  • NPM version: 6.14.5
  • Strapi version: 3.0.1
  • Database: Postgres 12.3
  • Operating system: Windows 10 Pro x64

Additional context
Seems to be a problem with how strapi is sending the redirect_uri to the Oauth providers. Shouldn't it be something like https://760bbe10e952.ngrok.io/connect/github/callback ?
image
image

I also noticed that, as opposed to the tutorial video, redirect URL field in the provider config doesn't get automatically populated, could it be a frontend issue?
image

If I try any other provider (tried facebook & google as well), I also get an URL related error.

@anis-marrouchi
Copy link

Hello @alexdevmotion, we have experienced a similar issue. In our case we did overwrite the extensions/users-permissions/controllers/Auth.js.
The issue happened after we've migrated to version 3.0.1.

To fix this issue we've updated the Auth.js with the updated version found under
node_modules/strapi-plugin-users-permissions/controllers/Auth.js.
Specifically these 2 lines (260-261)

grantConfig[provider].callback = _.get(ctx, 'query.callback') || grantConfig[provider].callback;
grantConfig[provider].redirect_uri =`${strapi.config.server.url}/connect/${provider}/callback`;

Hope this will resolve the problem for you and anyone else who is facing a similar issue.

@alexdevmotion
Copy link
Author

alexdevmotion commented Jun 7, 2020

@anis-marrouchi I don't have a extensions/users_permissions/controllers/Auth.js - it's using the one from node_modules which looks exactly like you have it there.

But from your code snippet, I deduce that ${strapi.config.server.url} is empty in my case. I'll have a look where this is set.

By the way, it wasn't related to the version, I had the same issue w/ 3.0.0.

Thanks!

Later edit
Yup, it seems like my strapi.config.server looks like this:

{
  host: '0.0.0.0',
  port: 1337,
  cron: { enabled: false },
  admin: { autoOpen: false },
  url: ''
}

I'll investigate further.

Laterer edit
The docs say that the url, if not serving via proxy, should basically be the prefix for the API, so it's fine to be empty.

Can someone help shed some light on this issue?

@alexdevmotion
Copy link
Author

Okay, so, if anyone is also having this issue, here is some progress I made on it:

If I manually change line 261 in node_modules/strapi-plugin-users-permissions/controllers/Auth.js from

grantConfig[provider].redirect_uri = `${strapi.config.server.url}/connect/${provider}/callback`;

to

grantConfig[provider].redirect_uri = `https://baae71593e94.ngrok.io/connect/facebook`;

which is the ngrok URL to the react login example app, running on port 3000 on my machine.
And also setting the same redirect URL in the Github / Facebook Oauth config.

Then, I'm able to successfully reach the Oauth authentication screen for both Github and Facebook, after clicking the corresponding buttons in the react login app.
Then, they successfully respond with the code, which reaches my frontend, which in term makes a call to http://localhost:1337/connect/{github or facebook}/callback?code={whatever code}.

All seems fine until now, but the backend responds with an error. For facebook this error is:
image

And for github, this error is:
image

Maybe this helps in narrowing down the cause of the bug. Could there have been changes made to Grant or how the Oauth providers work lately?

Thanks in advance!

@Kabil-Boutou
Copy link

Hi @alexdevmotion, there is a better solution than changing the node modules file.
You can just add the url in config > server.js ( if you don't have the folder just creat if with server.js file ) and in the file add this : module.exports = ({ env }) => ({ url: "http://localhost:1337", });
It should work just fine.

@alexdevmotion
Copy link
Author

@Kabil-Boutou I would clearly not go with the approach of modifying a file inside node_modules, I was just using it as a means to convey the problem I'm facing and how I made progress in solving it.

Setting the url to http://localhost:1337 was one of the first things I tried, but to no avail.

Thanks!

@akhilmhdh
Copy link
Contributor

@alexdevmotion did you find a fix. I am also stuck at this issue. After migrating my oauth is not working. Added url but the problem is after authentication redirection i am not getting JSON instead getting query parameters of id_token etc. The user is not saved at all.

@alexdevmotion
Copy link
Author

Nope I have not, I'm still waiting from feedback from other contributors. However, it seems that the problem you are encountering @akhilmhdh is different.

@lauriejim lauriejim added severity: high If it breaks the basic use of the product source: plugin:users-permissions Source is plugin/users-permissions package status: confirmed Confirmed by a Strapi Team member or multiple community members issue: bug Issue reporting a bug labels Jun 16, 2020
@petersg83
Copy link
Contributor

Hi!
I think the doc should be updated to be clearer.
Yes url in config/server.js is required to use the connect feature, and have to be absolute like "https://mywebsite.com".
Otherwise we don't know how to construct this url.
Let me know if that works for you!

You can set

{
  host: '0.0.0.0',
  port: 1337,
  cron: { enabled: false },
  admin: { autoOpen: false },
  url: 'https://760bbe10e952.ngrok.io'
}

@alt-ctrl-dev
Copy link

alt-ctrl-dev commented Jun 18, 2020

I found that setting 'url' changes the url strapi admin should also point to. This could be an issue if the callback url points to a url that is not strapi

e.g. if you set url as

 {
  host: '0.0.0.0',
  port: 1337,
  cron: { enabled: false },
  admin: { autoOpen: false },
  url: 'https://760bbe10e952.ngrok.io'
}

then strapi thinks that https://760bbe10e952.ngrok.io/admin point to http://localhost:1337/admin

@alt-ctrl-dev
Copy link

I've just made a PR to fix this for github, facebook and google. May need fixing the rest.

Also, I created a file called provider.js under ./config

module.exports = ({ env }) => ({
    github:{
        redirect_url:env('GITHUB_CALLBACK_HOST', ''),
        client_secret:env('GITHUB_CLIENT_SECRET', ''),
        client_id:env('GITHUB_CLIENT_ID', ''),
    },
    facebook:{
        ...
    },
    ...
  });

This allow to override values in the user-permission plugin

@superoo7
Copy link

Are there any temporary fix for this without changing the node_modules?

@alt-ctrl-dev
Copy link

You can copy the changed files and place them ./extensions/user-permissions/**

@iicdii
Copy link
Contributor

iicdii commented Jun 24, 2020

grantConfig[provider].redirect_uri = `${strapi.config.server.url}/connect/${provider}/callback`;

I think ${strapi.config.server.url} needs to be changed. It has a problem when using proxy port for like nginx. In my case I use https://example.com:8000 in production and it causes redirect_uri_mismatch error.

@alt-ctrl-dev
Copy link

alt-ctrl-dev commented Jun 24, 2020

@iicdii in the pull request made, I suggested the following change:
grantConfig[provider].redirect_uri = (strapi.config.provider && strapi.config.provider[provider] && strapi.config.provider[provider].redirect_url) || ${strapi.config.server.url}/connect/${provider}/callback;

@iicdii
Copy link
Contributor

iicdii commented Jun 24, 2020

@reubenkcoutinho That will solve the problem.

@iicdii
Copy link
Contributor

iicdii commented Jun 25, 2020

For now, I just created /extension/users-permissions/controllers/Auth.js to override method.

'use strict';

/**
 * Auth.js controller
 *
 * @description: A set of functions called "actions" for managing `Auth`.
 */

/* eslint-disable no-useless-escape */
const _ = require('lodash');
const grant = require('grant-koa');

module.exports = {
  async connect(ctx, next) {
    const grantConfig = await strapi
      .store({
        environment: '',
        type: 'plugin',
        name: 'users-permissions',
        key: 'grant',
      })
      .get();

    const [requestPath] = ctx.request.url.split('?');
    const provider = requestPath.split('/')[2];

    if (!_.get(grantConfig[provider], 'enabled')) {
      return ctx.badRequest(null, 'This provider is disabled.');
    }
    // Ability to pass OAuth callback dynamically
    grantConfig[provider].callback = _.get(ctx, 'query.callback') || grantConfig[provider].callback;
    grantConfig[provider].redirect_uri = grantConfig[provider].redirect_uri || `${strapi.config.server.url}/connect/${provider}/callback`;

    return grant(grantConfig)(ctx, next);
  },
};

If you already set redirect uri in admin panel it will work.

@jonathanmach
Copy link

jonathanmach commented Jun 25, 2020

I'm facing the same issue here, trying to configure Google as a provider.

image (1)

image

@jonathanmach
Copy link

Hi!
I think the doc should be updated to be clearer.
Yes url in config/server.js is required to use the connect feature, and have to be absolute like "https://mywebsite.com".
Otherwise we don't know how to construct this url.
Let me know if that works for you!

You can set

{
  host: '0.0.0.0',
  port: 1337,
  cron: { enabled: false },
  admin: { autoOpen: false },
  url: 'https://760bbe10e952.ngrok.io'
}

Just found this!

@jonathanmach
Copy link

jonathanmach commented Jun 26, 2020

@alexdevmotion did you find a fix. I am also stuck at this issue. After migrating my oauth is not working. Added url but the problem is after authentication redirection i am not getting JSON instead getting query parameters of id_token etc. The user is not saved at all.

@akhilmhdh I'm facing the same issue - did manage to make any progress on this?

@akhilmhdh
Copy link
Contributor

akhilmhdh commented Jun 26, 2020

@jonathanmach Yah i fixed it. Basically i did exactly as you given above. Added my domain host and port as url in env format for production and development. Then it changed relative to absolute for callback. Ohhhh ok I think i know what your all bothered. Ok so basically the redirect uri is not what you think it is. The redirect url must be provider/auth/callback. Then your user will be saved properly. In front end after auth your will get an ID send that to this url. You will get json formated data of your user with jwt.

https://blog.strapi.io/protected-routes-and-authentication-with-react-and-node-js/

Check this tutorial. Go to Here is the flow: section. You will get your ans there.

@jonathanmach
Copy link

@akhilmhdh YOU ARE A LIFE SAVIOR!
Thank you so much. The article does make things clearer! Specially regarding the flow, I think that's what was getting me stuck.
I wish they had a link to it in the original docs.

Thank you once again!

@akhilmhdh
Copy link
Contributor

@jonathanmach Lol sure man ✌️

@frostyk
Copy link

frostyk commented Jul 21, 2020

After setting url in config/env/production/server.js admin in production stop working..
It uses localhost:1337 as request url for some reasons...

Do you have any ideas how to fix it?

@petersg83
Copy link
Contributor

Hi, can you specify what uses localhost:1337 as request url?
I updated the documentation to make it clearer. I also created an example-app. You can check this here for the moment #7132

@petersg83 petersg83 added severity: low If the issue only affects a very niche base of users and an easily implemented workaround can solve source: docs Documentation changes and removed severity: high If it breaks the basic use of the product issue: bug Issue reporting a bug labels Jul 29, 2020
@alexdevmotion
Copy link
Author

@petersg83 The Auth controller inside strapi-plugin-users-permissions uses strapi.config.server.url to generate the redirect_uri:

grantConfig[provider].redirect_uri = `${strapi.config.server.url}/connect/${provider}/callback`;

That is why the url needs to be configured inside the config/server.js file.
I do confirm that after the latest updates to the plugin and after adding this to the server config file, the auth providers seem to work fine.

@GabeL7r
Copy link

GabeL7r commented Aug 2, 2020

Should there be a user created in strapi after successful authentication?

I am using the GitHub provider and I am able to go through the authentication flow by setting url in config/server.js. I verify at the end of the flow I get a redirect with the GitHub access token, however, there is no new user in Strapi. Are we supposed to implement the logic to create a user?

@lauriejim
Copy link
Contributor

Please check this file in the PR - https://github.com/strapi/strapi/pull/7132/files#diff-8434e8f791257802c2af54d99bc2f32d
This is the new detail about the auth process. You are in the middle of the process, you should request the Strapi backend with this token.
Please check the docs for more information.

@derrickmehaffy
Copy link
Member

This issue has been mentioned on Strapi Community Forum. There might be relevant details there:

https://forum.strapi.io/t/use-of-jwt-in-httponly-cookie-4632/1865/6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
severity: low If the issue only affects a very niche base of users and an easily implemented workaround can solve source: docs Documentation changes source: plugin:users-permissions Source is plugin/users-permissions package status: confirmed Confirmed by a Strapi Team member or multiple community members
Projects
None yet
Development

Successfully merging a pull request may close this issue.