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

handling invalid token without raising Exception #22

Closed
slashmili opened this issue Aug 1, 2016 · 3 comments
Closed

handling invalid token without raising Exception #22

slashmili opened this issue Aug 1, 2016 · 3 comments

Comments

@slashmili
Copy link

What do you think of returning false when the token is invalid instead of raising ArgumentError?

jwk = %{
  "kty" => "oct",
  "k" => :base64url.encode("symmetric key")
}

{false, _, _} = JOSE.JWT.verify(jwk, "invalid")

I'm suggesting that because feels more natural and also make it much easier to use with pipes in Elixir.

@rlopzc
Copy link

rlopzc commented Aug 1, 2016

@slashmili how did you manage the Argument error?

I made this, what do you think?

def from_token(token) do
    jwk_key = Application.get_env(:soranus, :ec_private_jwk).()
    try do
      case JOSE.JWK.verify(token, jwk_key) do
        {true, "User:"<> id, _} -> id
        _ -> nil
      end
    rescue ArgumentError ->
      nil
    end
  end

@slashmili
Copy link
Author

slashmili commented Aug 2, 2016

More or less, if you look at the way that Elixir/Erlang handles "valid" errors is more like this :

iex(1)> File.read("/tmp/invalidfile")
{:error, :enoent}

So what I use is like this:

  defp verify_token(token) do
    try do
      JWT.verify(@invitation_jwk, token)
    rescue
      e -> e
    end
  end

  def validate_my_token(token) do
    with {true, %JWT{fields: data}, _} <- verify_token(token) do
      {:ok, data}
    else
      {false, jwt, jws} -> {:error, :not_verified}
      e -> {:error, e}
    end
  end

What I would like to see from this library is to return like this:

{:ok, _, _} = JWT.verify(@invitation_jwk, valid_token)
{:error, _, _} = JWT.verify(@invitation_jwk, invalid_token)

potatosalad added a commit that referenced this issue Aug 9, 2016
* Enhancements
  * ChaCha20/Poly1305 encryption and one-time message authentication
    functions are experimentally supported based on RFC 7539.

* Fixes
  * Handling invalid token without raising Exception #22
  * JOSE.JWT.verify uses CPU intensively when signed is nil #23
@potatosalad
Copy link
Owner

Version 1.8.0 of jose essentially just captures the thrown exceptions and returns then as an :error tuple for now.

I would like to refactor the project to return things similar to what @slashmili suggested, but the amount of refactoring required might be better suited for the next major version of the project.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants