Knock: Custom login response

Created on 18 Nov 2016  路  3Comments  路  Source: nsarno/knock

Hello,

I would like to know if it is possible to get a custom login response like:

{
  "jwt": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0ODAwMjg3MDUsInN1YiI6Mn0._eQ8oXkOkV5E-bhKbAKR_FnbCdWK4LJvNUHHvy-H5Q0",
  "user": {
    "id": 1,
    "email": "[email protected]",
    "name": "John",
    "location": "....",
  } 
}

instead of:

{
  "jwt": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0ODAwMjg3MDUsInN1YiI6Mn0._eQ8oXkOkV5E-bhKbAKR_FnbCdWK4LJvNUHHvy-H5Q0"
}

Thank you,
YM

All 3 comments

Disclaimer: I'm new to Knock and just trying to understand how it all hangs together :)

The whole point of using JWTs is that you can encode arbitrary claims in it, so the idea is that you decode the token on the client to access the data. See jwt.io, your token contains the following payload:

{
  "exp": 1480028705,
  "sub": 2
}

See the section "Modify the token payload" in the README on how to extend the data.

If you want to keep the token small and return the data separately, it looks like you can just overwrite the create action in your token controller.

@YMonnier Have a look at the code of the token controller. As @toupeira suggested, you can override the #create method to fit your needs.

If you ever run into this - Here is a solution for you.
Add this after UserTokenController class in user_token_controller.rub

Knock::AuthTokenController.class_eval do

  def create
    user = User.find(entity.id)
    render json: {
        jwt: auth_token.token,
        company_name: user.company_name,
        name: user.name,
        invoice_settings: user.invoice_settings
      }, status: :created
  end

end
Was this page helpful?
0 / 5 - 0 ratings