http://127.0.0.1:9292/oauth/apps/new
get '/test' do
client_id = '3z8kv2day1vi3o41wkuzh783l'
client_secret = 'f1kb2o0ufgo6kyu3k8d9wf9va'
code = params[:code]
# 将authorize_code换为access_token,同一code只能换取一次
# 换取path一般为/oauth/token,而oauth2-provider使用与获取code相同的path:authorize
get_access_code = Net::HTTP.post_form(URI.parse('http://127.0.0.1:9292/oauth/authorize'), {client_id: client_id, client_secret: client_secret, redirect_uri: 'http://127.0.0.1:9293/test', grant_type: 'authorization_code', code: code})
result = JSON.parse(get_access_code.response.body)
# 通过access_token访问受限资源
Net::HTTP.get(URI.parse("http://127.0.0.1:9292/me?oauth_token=#{result['access_token']}"))
end
# 使用oauth2 gem获取access_token
# 获取authorize_code
redirect_to client.web_server.authorize_url(
redirect_uri: Theme.redirect_uri,
state: "name__style"
)
# 获取access_token
access_token = client.web_server.get_access_token params[:code], redirect_uri: Theme.redirect_uri
me = access_token.get('/api/me') # 通过access_token访问受限资源
protected
def client
@client ||= OAuth2::Client.new(
Theme.client_id,
Theme.client_secret,
site: 'http://lvh.me:4001'
)
end