ueberauth / guardian

Elixir Authentication
MIT License
3.43k stars 382 forks source link

How to mitigate invalid_token error when using different secret keys on the same domain #608

Closed ospaarmann closed 5 years ago

ospaarmann commented 5 years ago

I use Guardian to protect two different scopes in a phoenix app. One for members, one for admins. I set up guardian for both, using different configurations and secret keys:

# Configures Guardian member authentication
config :my_app, MyApp.Members.Auth.Guardian,
  issuer: "my_app",
  secret_key: "<SECRET_KEY_1>",
  verify_issuer: true

# Configures Guardian admin authentication
config :my_app, MyApp.Admins.Auth.Guardian,,
  issuer: "my_app",
  secret_key: "<SECRET_KEY_2>",
  verify_issuer: true

Now when I log into /admin and then try to access /members, I receive an invalid_token error. This seems to come from

https://github.com/ueberauth/guardian/blob/b6c6deed44fac615fb839df0297aa1e522773b4a/test/support/token_module.ex#L95

What seems to happen is that Guardian tries to decode the token but finds it invalid because the secret_key is different.

What should happen is that Guardian realizes this token is not for this scope and not even try to decode it. What should I look into to solve this issue?

ospaarmann commented 5 years ago

Nevermind, I found the option key. To make this work, you just need to place the tokens under a different key for each scope. So in my SessionController I now write:

Guardian.Plug.sign_in(conn, admin, %{}, key: :admin)

And in my pipeline implementation I need to add the key as an option that the token can be fetched from the connection again:

use Guardian.Plug.Pipeline,
    otp_app: :my_app,
    error_handler: MyApp.Auth.ErrorHandler,
    module: MyApp.Admins.Auth.Guardian,
    key: :admin