Facebook token expiration and renewal, with Koala and omniauth-facebook

前端 未结 3 1897
时光取名叫无心
时光取名叫无心 2020-12-07 16:55

I\'m writing a Rails app that uses omniauth-facebook to authenticate the user against FB (and to get a FB OAuth access token for the user). The app then uses Koala to make

3条回答
  •  有刺的猬
    2020-12-07 17:45

    You can do something like this where you check if the access_token is expired and generate another one.

     %w[facebook].each do |provider|
       scope provider, -> { where(provider: provider) }
     end
    
     def client
       send("#{provider}_client")
     end
    
     def expired?
       expires_at? && expires_at <= Time.zone.now
     end
    
     def access_token
       send("#{provider}_refresh_token!", super) if expired?
       super
     end
    
     def facebook_refresh_token!(token)
       new_token_info = 
       Koala::Facebook::OAuth.new.exchange_access_token_info(token)
       update(access_token: new_token_info["access_token"], expires_at: Time.zone.now + new_token_info["expires_in"])
     end
    

    You can check gorails screencast that explains this on depth.

提交回复
热议问题