0

In my app, I added in User model a field twilio_video_token as a string.
When comes the time to create a token associated to a specific user, I do that:

token = Twilio::JWT::AccessToken.new ENV["TWILIO_ACCOUNT_SID"], ENV["TWILIO_API_KEY"], ENV["TWILIO_API_SECRET"], ttl: 3600, identity: @user.name
@user.twilio_video_token = token.to_jwt
@user.save

Then, later in my app, I have an instance of a specific user.
So I access to his token like this : @user.twilio_video_token, but it's a string, so I can't read informations stored in the token (like identity or grants).
How could I convert this string to be back a Twilio::JWT::AccessToken object?


What I tried:
Using 'jwt' gem

@token = JWT.decode current_user.twilio_video_token, ENV["TWILIO_API_SECRET"], true, { algorithm: 'HS256' }

But it's a mess...
When I print @token, I see identity into grants !!

[{"jti"=>"SK****", "grants"=>{"identity"=>"Sylvain"}, "iss"=>"SK****", "nbf"=>1587406278, "exp"=>1587409878, "sub"=>"AC***"}, {"cty"=>"twilio-fpa;v=1", "typ"=>"JWT", "alg"=>"HS256"}]

I have to confess, I see Twilio doc as a huge labyrinth! I'm into it, but I can't tell where I am!

Thanks a lot for your help
Sylvain

1 Answers1

0

You are missing the grant array argument for Twilio::JWT::AccessToken.new It should look like:

token = Twilio::JWT::AccessToken.new(
  ENV["TWILIO_ACCOUNT_SID"], 
  ENV["TWILIO_API_KEY"], 
  ENV["TWILIO_API_SECRET"],
  [grant],  
  ttl: 3600, 
  identity: @user.name
)

where grant could be Twilio::JWT::AccessToken::VoiceGrant.new as an example.

See Twilio API: Access Tokens

I never used the Twilio API but for me it looks like as you should not save the token to a user record, because these tokens have a TTL which means you would have to update the user record each time the token is changed.

I hope this helps.

Bests Flo

Flo
  • 540
  • 6
  • 20
  • You don't have to set grants when creating a new token. If you don't then `token.grants` value is an empty array `[]`. You can set grant one by one later. Maybe you're right about not saving token in DB, I'll see how it goes! – Sylvain FARNAULT Apr 24 '20 at 12:48