`
hot88zh
  • 浏览: 182791 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

oauth GEM的几个小例子

阅读更多

1、注册并认证你的应用

 

#!/usr/bin/ruby
 
# Get all the auth details you need
# You wouldn't actually do it this way, but hey.
# Normally you'd distribute the consumer stuff with your
# application, and each user gets the access_token stuff
# But hey, this is just a demo.
 
require 'rubygems'
require 'oauth'
require 'yaml'
 
# Format of auth.yml:
# consumer_key: (from osm.org)
# consumer_secret: (from osm.org)
# token: (use oauth setup flow to get this)
# token_secret: (use oauth setup flow to get this)
auth={}
 
puts "First, go register a new application at "
puts "http://api06.dev.openstreetmap.org/oauth_clients/new"
puts "Tick the appropriate boxes"
puts "Enter the consumer key you are assigned:"
auth["consumer_key"] = gets.strip
puts "Enter the consumer secret you are assigned:"
auth["consumer_secret"] = gets.strip
puts "Your application is now set up, but you need to register"
puts "this instance of it with your user account."
 
@consumer=OAuth::Consumer.new auth["consumer_key"], 
                              auth["consumer_secret"], 
                              {:site=>"http://api06.dev.openstreetmap.org"}
 
@request_token = @consumer.get_request_token
 
puts "Visit the following URL, log in if you need to, and authorize the app"
puts @request_token.authorize_url
puts "When you've authorized that token, enter the verifier code you are assigned:"
verifier = gets.strip                                                                                                                                                               
puts "Converting request token into access token..."                                                                                                                                
@access_token=@request_token.get_access_token(:oauth_verifier => verifier)                                                                                                          
 
auth["token"] = @access_token.token
auth["token_secret"] = @access_token.secret
 
File.open('auth.yaml', 'w') {|f| YAML.dump(auth, f)}
 
puts "Done. Have a look at auth.yaml to see what's there."
 

 

2、创建简单的HTTP请求

 

#!/usr/bin/ruby
 
# Simple OSM Auth example showing GET PUT and DELETE methods
# Requires OAuth rubygem
 
require 'rubygems'
require 'oauth'
require 'date'
require 'yaml'
 
# Format of auth.yml:
# consumer_key: (from osm.org)
# consumer_secret: (from osm.org)
# token: (use oauth setup flow to get this)
# token_secret: (use oauth setup flow to get this)
auth = YAML.load(File.open('auth.yaml'))
 
# The consumer key and consumer secret are the identifiers for this particular application, and are 
# issued when the application is registered with the site. Use your own.
@consumer=OAuth::Consumer.new auth['consumer_key'], 
                              auth['consumer_secret'], 
                              {:site=>"http://api06.dev.openstreetmap.org"}
 
# Create the access_token for all traffic
@access_token = OAuth::AccessToken.new(@consumer, auth['token'], auth['token_secret']) 
 
# Use the access token for various commands. Although these take plain strings, other API methods 
# will take XML documents.
@access_token.put('/api/0.6/user/preferences/demo_last_run_time', DateTime.now().to_s, {'Content-Type' => 'text/plain' })
@access_token.put('/api/0.6/user/preferences/deleteme', "This shouldn't be seen", {'Content-Type' => 'text/plain' })
@access_token.delete('/api/0.6/user/preferences/deleteme')
puts @access_token.get('/api/0.6/user/preferences').body
 

3、表单上传文件

 

#!/usr/bin/ruby
 
# hacky script for uploading a file to the OSM GPX api. 
# liberally stolen^Winspired by http://gist.github.com/97756
#
# Format of auth.yml:
# consumer_key: (from osm.org)
# consumer_secret: (from osm.org)
# token: (use oauth setup flow to get this)
# token_secret: (use oauth setup flow to get this)
 
require 'rubygems'
require 'oauth'
require 'xml/libxml'
require 'date'
 
CRLF = "\r\n"
endpoint_gpx_create = 'http://api06.dev.openstreetmap.org/api/0.6/gpx/create'
 
if ARGV.size < 1
  puts "Usage: #{$0} path_to_gpx_file"
  puts "e.g. #{$0} /home/gravitystorm/osm/tracks/20081128.gpx"
  exit(1)
end
 
# Take GPX file from commandline argument
file = File.new(ARGV[0])
 
# Format of auth.yml:
# consumer_key: (from osm.org)
# consumer_secret: (from osm.org)
# token: (use oauth setup flow to get this)
# token_secret: (use oauth setup flow to get this)
auth = YAML.load(File.open('auth.yaml'))
 
@consumer=OAuth::Consumer.new auth['consumer_key'], 
                              auth['consumer_secret'], 
                              {:site=>"http://api06.dev.openstreetmap.org"}
 
@access_token = OAuth::AccessToken.new(@consumer, auth['token'], auth['token_secret']) 
 
# Encodes the request as multipart
def add_multipart_data(req,params)
  boundary = Time.now.to_i.to_s(16)
  req["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
  body = ""
  params.each do |key,value|
    esc_key = CGI.escape(key.to_s)
    body << "--#{boundary}#{CRLF}"
    if value.respond_to?(:read)
      body << "Content-Disposition: form-data; name=\"#{esc_key}\"; filename=\"#{File.basename(value.path)}\"#{CRLF}"
      body << "Content-Type: text/xml#{CRLF*2}"
      body << value.read
    else
      body << "Content-Disposition: form-data; name=\"#{esc_key}\"#{CRLF*2}#{value}"
    end
    body << CRLF
  end
  body << "--#{boundary}--#{CRLF*2}"
  req.body = body
  req["Content-Length"] = req.body.size
end
 
# Uses the OAuth gem to add the signed Authorization header
def add_oauth(req)
  @consumer.sign!(req,@access_token)
end
 
#Actually do the request and print out the response
url = URI.parse(endpoint_gpx_create)
Net::HTTP.new(url.host, url.port).start do |http|
  req = Net::HTTP::Post.new(url.request_uri)
  add_multipart_data(req,:file=>file, :tags=>'heheheheh', :description=>'upside down', :public=>'1')
  add_oauth(req)
  res = http.request(req)
  puts res.body
end
 
分享到:
评论

相关推荐

    OAuth gem for rails3

    OAuth gem for Rails3 是一个针对Ruby on Rails框架的授权库,它实现了OAuth协议,以便于在Rails应用中安全地处理第三方服务的授权流程。OAuth是一个开放标准,允许用户让第三方应用在无需分享用户名和密码的情况下...

    spring oauth2.0 例子

    这个"spring oauth2.0 例子"是一个在MyEclipse集成开发环境中创建的示例项目,用于演示如何在Spring框架中实现OAuth2.0认证和授权流程。 首先,OAuth2.0的核心概念包括客户端、资源所有者(用户)、授权服务器和...

    一个OAuth授权的一个例子,实现了三种常用的授权方式

    OAuth(开放授权)是一种开放标准,允许用户让第三方应用在不分享用户名密码的情况下,安全地...通过分析和学习这个例子,开发者可以更好地理解和应用OAuth协议,为自己的应用添加安全的第三方登录或者数据访问功能。

    oauth2 php客户端的例子

    OAuth 2.0 is the next evolution of the OAuth protocol which was originally created in late 2006. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web ...

    oauth jersey实现例子

    在这个"oauth jersey实现例子"中,我们将探讨如何结合OAuth和Jersey构建安全的RESTful API。 首先,OAuth的核心概念包括资源所有者(Resource Owner)、客户端(Client)、授权服务器(Authorization Server)和...

    oauth2.0例子

    在这个例子中,tonr和sparklr可能是两个独立的服务,但通过OAuth 2.0,用户只需登录一次就可以在两个系统间无缝切换。SSO减少了用户的登录负担,提高了用户体验。 3. tonr项目:作为客户端应用,tonr需要实现OAuth ...

    spring boot security oauth2例子

    一个springboot为框架的security oauth2应用例子,同时集成了swagger2的 restful API查看页面,druid数据源监控, mybatis自动生成和分页插件,远程资源服务器的认证和授权,也可以去github下载 ...

    springboot与security oauth2整合例子

    在这个例子中,我们首先需要在Spring Boot项目中引入Spring Security和Spring Security OAuth2的依赖。在`pom.xml`文件中添加相应的Maven坐标: ```xml &lt;groupId&gt;org.springframework.boot &lt;artifactId&gt;spring...

    netcore+webapi+jwt+oauth2+swagger的例子

    解决方案包含五个项目 1.WebApiClient:控制台调用接口项目 2.WebApiTest:.NetCore+jwt+swagger编写的接口 3.WebApiTest.ApiOauth2:.Net4.5+oauth2+swagger编写的接口 4.WebApiTest.ApiController:.Net4.5+jwt+...

    完整Oauth 2.0实现实例

    OAuth 2.0 主要分为四个角色:资源所有者(Resource Owner)、客户端(Client)、授权服务器(Authorization Server)和资源服务器(Resource Server)。资源所有者是拥有数据的用户,客户端是请求访问这些资源的...

    spring security oauth 2.0 例子

    在这个例子中,我们将深入探讨如何在Spring Security OAuth 2.0中使用客户端模式,并且如何将`client_id`存储在数据库中,而非硬编码在配置文件里。 OAuth 2.0 是一种授权框架,允许第三方应用(客户端)在用户许可...

    Oauth认证的简单例子

    Oauth认证的简单例子,很适合新手学习

    php-oauth一个简单的oauth实现

    在PHP中实现OAuth,我们可以使用一些现有的库,例如这个例子中的"php-oauth"。 在PHP中实现OAuth,我们需要理解以下几个核心概念: 1. **客户端(Client)**:这是请求访问资源的第三方应用,如社交媒体分析工具或...

    oauth+springmvc小demo

    在这个"oauth+springmvc小demo"中,我们将会探讨如何将 OAuth 身份验证框架与 SpringMVC 框架结合起来,创建一个安全的、可扩展的应用程序。 OAuth 是一个授权协议,它允许第三方应用在用户许可的情况下访问特定的...

    oauth2.0例子(淘宝)

    通过学习这个例子,开发者可以了解OAuth 2.0的实际应用,掌握如何与淘宝API进行交互,从而实现诸如登录授权、获取用户信息、管理订单等功能。同时,这也为与其他使用OAuth 2.0的服务提供商进行集成提供了参考。

    oauth核心jar包

    在这个"oauth核心jar包"中,包含了OAuth2框架的关键组件,用于构建客户端和服务端的应用。 首先,`oauth2.resourceserver`这个标签可能指的是OAuth2资源服务器的实现。资源服务器是存储受保护资源的地方,只有在...

    Ruby-OAuth2一个OAuth20协议的Ruby封装

    OAuth 2.0流程主要包括以下几个步骤: 1. **授权请求**:用户通过客户端(如应用)被引导到授权服务器,请求访问权限。 2. **用户授权**:用户在授权服务器上登录并同意或拒绝授予客户端权限。 3. **授权码**:如果...

    Spring security oauth源码

    Spring Security OAuth 是一个用于保护RESTful Web服务的框架,它为OAuth 1.0a和OAuth 2.0协议提供了全面的支持。在这个源码中,我们可能会看到如何将Spring Security与OAuth结合,以构建安全的Web应用程序和服务。...

    nodejs oauth 2 例子代码

    nodejs 搭建oauth服务器的代码 Install nodejs and npm and then, simply run npm install and npm start. The server should now be running at http://localhost:3000.

    omniauth-shopify-oauth2, OmniAuth 1.0的Shopify OAuth2策略.zip

    omniauth-shopify-oauth2, OmniAuth 1.0的Shopify OAuth2策略 OmniAuth ShopifyOmniAuth 1.0的Shopify OAuth2策略。安装添加到你的Gemfile:gem 'omniauth-shopify-oauth2'然后 bundle instal

Global site tag (gtag.js) - Google Analytics