我正在尝试编写一个基于oauth2 gem的简单OAuth2客户端。我们的想法是在会话中存储访问令牌,并在每次请求之前检查它是否未过期。
以下获取新令牌的代码如下:
client = OAuth2::Client.new(
'26b8e5c92367d703ad35a2fc16b14dc93327a15798068ccba473aa2e3d897883',
'b16079915cdc20b5373f1601e31cece5a84274f772cfd89aec12c90fd110775e',
site: 'http://localhost:3000'
)
client.client_credentials.get_token.expired?
它工作正常。对我的api的请求被触发,最后一行显示令牌是否已过期。问题是当我试图自己恢复令牌状态时:
OAuth2::AccessToken.new(client, session[:api_token]).expired?
这行代码不会向我的api发出请求,因此,不知道令牌生命周期是什么,expires_at param还是其他任何东西。 “令牌”参数之外的所有内容都是零,因此expired?
方法始终返回false
:
#<OAuth2::AccessToken:0x007fad4c9e2e28 @client=#<OAuth2::Client:0x007fad4ddb7160 @id="26b8e5c92367d703ad35a2fc16b14dc93327a15798068ccba473aa2e3d897883", @secret="b16079915cdc20b5373f1601e31cece5a84274f772cfd89aec12c90fd110775e", @site="http://localhost:3000", @options={:authorize_url=>"/oauth/authorize", :token_url=>"/oauth/token", :token_method=>:post, :connection_opts=>{}, :connection_build=>nil, :max_redirects=>5, :raise_errors=>true}, @client_credentials=#<OAuth2::Strategy::ClientCredentials:0x007fad4ddb6f80 @client=#<OAuth2::Client:0x007fad4ddb7160 ...>>, @connection=#<Faraday::Connection:0x007fad4ddb6738 @headers={"User-Agent"=>"Faraday v0.8.8"}, @params={}, @options={}, @ssl={}, @parallel_manager=nil, @default_parallel_manager=nil, @builder=#<Faraday::Builder:0x007fad4ddb6620 @handlers=[Faraday::Request::UrlEncoded, Faraday::Adapter::NetHttp]>, @url_prefix=#<URI::HTTP:0x007fad4ddb60d0 URL:http://localhost:3000/>, @proxy=nil, @app=#<Faraday::Request::UrlEncoded:0x007fad4ddb4190 @app=#<Faraday::Adapter::NetHttp:0x007fad4ddb4280 @app=#<Proc:0x007fad4ddb4370@/usr/local/rvm/gems/ruby-2.0.0-p247/gems/faraday-0.8.8/lib/faraday/connection.rb:93 (lambda)>>>>>, @token="114781bdace77fa7f4629e2b42dbe68ac73326728dddc8102b9c2269e3e86a36", @refresh_token=nil, @expires_in=nil, @expires_at=nil, @options={:mode=>:header, :header_format=>"Bearer %s", :param_name=>"access_token"}, @params={}>
我做错了什么或是某种错误?总而言之:我需要检查存储在会话中的令牌(作为字符串)是否已过期。
答案 0 :(得分:2)
如果检查AccessToken的代码,则必须传递包含“expires_at”值的第三个参数(选项),该值在您调用过期时使用? :
def initialize(client, token, opts={})
@client = client
@token = token.to_s
[:refresh_token, :expires_in, :expires_at].each do |arg|
instance_variable_set("@#{arg}", opts.delete(arg) || opts.delete(arg.to_s))
end
@expires_in ||= opts.delete('expires')
@expires_in &&= @expires_in.to_i
@expires_at &&= @expires_at.to_i
@expires_at ||= Time.now.to_i + @expires_in if @expires_in
@options = {:mode => opts.delete(:mode) || :header,
:header_format => opts.delete(:header_format) || 'Bearer %s',
:param_name => opts.delete(:param_name) || 'access_token'}
@params = opts
end
...
def expired?
expires? && (expires_at < Time.now.to_i)
end
来源:https://github.com/intridea/oauth2/blob/master/lib/oauth2/access_token.rb#L42
因此,请将您的代码更新为:
OAuth2::AccessToken.new(client, session[:api_token], {expires_at: session[:expires_at]}).expired?