Skip to content

Instantly share code, notes, and snippets.

@saberma
Created July 17, 2011 09:49
Show Gist options
  • Save saberma/1087406 to your computer and use it in GitHub Desktop.
Save saberma/1087406 to your computer and use it in GitHub Desktop.

先访问以下地址,填写name和redirect_url,注册client,获取client_id,client_secret

http://127.0.0.1:9292/oauth/apps/new

获取authorize_code

redirect_uri要保持与注册client时填写的一致,获取authorize_code和获取access_code时redirect_url参数也要一致

http://127.0.0.1:9292/oauth/authorize?response_type=code&client_id=3z8kv2day1vi3o41wkuzh783l&redirect_uri=http%3A%2F%2F127.0.0.1%3A9293%2ftest

client服务

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment