How to get omniauth hash if I already have the access_token? - ruby-on-rails

Currently I have it implemented like so.
def auth_hash
url = URI.parse('https://graph.facebook.com/me')
url.query = URI.encode_www_form('access_token' => #token, 'fields' => 'email, name, first_name, last_name, gender')
req = Net::HTTP::Get.new url.request_uri
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = nil
http.start do |get|
response = get.request(req)
end
response
end
My IOS app does the callbacks and sends the access token to authenticated with our server.
I use the method above and it returns the hash from the graph api and I get the user info perfectly.
This method that I've used but it's not utilizing omniauth. So my question is there a way to retrieve the omniauth hash using only the generated access_token (the token is generated by the facebook sdk and sends it to the server)?
I'm just trying to make sure I'm not reinventing the wheel using this method.

There are few ruby gems for authentication with Facebook and retrieving data from it.
Please refer this link : https://github.com/arsduo/koala ,
https://github.com/nov/fb_graph2
And for google use can use refer this link: https://github.com/zquestz/omniauth-google-oauth2

Related

How safe is it to use an ip for running a Sinatra ruby app for an iOS application

I am building an iOS app and I have an AWS ec2 instance running a Sinatra app for refreshing and swapping a Spotify SDK access token and I am wondering about any safety issues with having a url such as http://#someIP:4567 on the application itself.
I know with an AWS ec2 instance you can get it secured by making it a https but how can you secure an IP in the same sense(If I even need to do so)?
Here is what is in the ruby file:
require 'sinatra'
require 'net/http'
require 'net/https'
require 'base64'
require 'encrypted_strings'
require 'json'
set :bind, '0.0.0.0'
CLIENT_ID = ENV['TheClientIDGivenBySpotify']
CLIENT_SECRET = ENV['TheClientSecretGivenBySpotify']
ENCRYPTION_SECRET = ENV['cFJLyifeUJUBFWdHzVbykfDmPHtLKLGzViHW9aHGmyTLD8hGXC']
CLIENT_CALLBACK_URL = ENV['appForSpotify://returnAfterLogin']
SPOTIFY_ACCOUNTS_ENDPOINT = URI.parse("https://accounts.spotify.com")
get '/' do
"Working"
end
post '/swap' do
AUTH_HEADER = "Basic " + Base64.strict_encode64(CLIENT_ID + ":" + CLIENT_SECRET)
# This call takes a single POST parameter, "code", which
# it combines with your client ID, secret and callback
# URL to get an OAuth token from the Spotify Auth Service,
# which it will pass back to the caller in a JSON payload.
auth_code = params[:code]
http = Net::HTTP.new(SPOTIFY_ACCOUNTS_ENDPOINT.host, SPOTIFY_ACCOUNTS_ENDPOINT.port)
http.use_ssl = true
request = Net::HTTP::Post.new("/api/token")
request.add_field("Authorization", AUTH_HEADER)
request.form_data = {
"grant_type" => "authorization_code",
"redirect_uri" => CLIENT_CALLBACK_URL,
"code" => auth_code
}
response = http.request(request)
# encrypt the refresh token before forwarding to the client
if response.code.to_i == 200
token_data = JSON.parse(response.body)
refresh_token = token_data["refresh_token"]
encrypted_token = refresh_token.encrypt(:symmetric, :password => ENCRYPTION_SECRET)
token_data["refresh_token"] = encrypted_token
response.body = JSON.dump(token_data)
end
status response.code.to_i
return response.body
end
post '/refresh' do
AUTH_HEADER = "Basic " + Base64.strict_encode64(CLIENT_ID + ":" + CLIENT_SECRET)
# Request a new access token using the POST:ed refresh token
http = Net::HTTP.new(SPOTIFY_ACCOUNTS_ENDPOINT.host, SPOTIFY_ACCOUNTS_ENDPOINT.port)
http.use_ssl = true
request = Net::HTTP::Post.new("/api/token")
request.add_field("Authorization", AUTH_HEADER)
encrypted_token = params[:refresh_token]
refresh_token = encrypted_token.decrypt(:symmetric, :password => ENCRYPTION_SECRET)
request.form_data = {
"grant_type" => "refresh_token",
"refresh_token" => refresh_token
}
response = http.request(request)
status response.code.to_i
return response.body
end
In xcode I would POST to http://#someIP:4567/swap or http://#someIP:4567/refresh
Is this safe to do?
Am I handling this correctly?
By having the request being sent to an IP that can be accessible by anyone, am I putting myself and anyone else who is using the application in danger of having their information stolen or viewed?
HTTPS is only available for domain names. Not available for IP. If you only use IP, then you are exposed to MITM attack and all your data is plain text flying around. Anyone can eavesdrop your request. You have a code parameter in the swap request and I guess is code is credential correct? If yes, it's better to grab some domain name and set it up using aws route53. Then buy some cheap SSL certificate to associate it with the domain. Then on the iOS side, enable HTTPS instead of HTTP to communicate with your server. This has nothing to do with your Sinatra app.
To know more about SSL/HTTPS, you can take a look at some beginner tutorials like this: http://www.hongkiat.com/blog/ssl-certs-guide/

Ruby github API

I am new to ruby programming. I was trying to write below ruby code to create a comment in Github gist.
uri = URI.parse("https://api.github.com/gists/xxxxxxxxxxx/comments")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = (uri.scheme == 'https')
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(uri.request_uri)
request.body = {
"body" => "Chef run failed "
}.to_json
response = http.request(request)
response2 = JSON.parse(response.body)
puts response2
But I executed below script then I always get {"message"=>"Not Found", "documentation_url"=>"https://developer.github.com/v3"}
Don't know what I am doing wrong. Appreciate help.
Make sure that you're authenticated first. From the Github API docs on Authentication:
There are three ways to authenticate through GitHub API v3. Requests
that require authentication will return 404 Not Found, instead of 403
Forbidden, in some places. This is to prevent the accidental leakage
of private repositories to unauthorized users.
You can do this by creating an OAuth2 token and setting it as an HTTP header:
request['Authorization'] = 'token YOUR_OAUTH_TOKEN'
You can also pass the OAuth2 token as a POST parameter:
uri.query = URI.encode_www_form(access_token: 'YOUR_OAUTH_TOKEN')
# Encoding really isn't necessary though for this though, so this should suffice
uri.query = 'access_token=YOUR_OAUTH_TOKEN'

Ruby and Twitter: Getting Access Token from Request Token?

I am currently in Step 3 of the processing on getting an oauth token/secret from an user trying to login via Twitter. https://dev.twitter.com/docs/auth/implementing-sign-twitter
Step 3 tells me to send this request to the API, but I am stuck as to how to do so. I currently have BOTH the oauth_token and oauth_verifier, but how do I send this POST request to get the oauth_token, oauth_token_secret pair?
Is there a standard Oauth Ruby gem I can use to send this POST request? I see examples online where I pass an #accessToken object, but i do not have such an object available. I just have the oauth_token and oauth_verifier (as strings). Given these 2 things, how do I convert them to an oauth_token and oauth_token_secret?
POST /oauth/access_token HTTP/1.1
User-Agent: themattharris' HTTP Client
Host: api.twitter.com
Accept: */*
Authorization: OAuth oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
oauth_nonce="a9900fe68e2573b27a37f10fbad6a755",
oauth_signature="39cipBtIOHEEnybAR4sATQTpl2I%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318467427",
oauth_token="NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0",
oauth_version="1.0"
Content-Length: 57
Content-Type: application/x-www-form-urlencoded
oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY
Try something like the following rails controller actions, using the twitter and oauth gems:
def redirect
consumer = OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET, {
:site => "https://api.twitter.com",
:scheme => :header
})
request_token = consumer.get_request_token(:oauth_callback => CALLBACK_URL)
session[:twitter_request_token] = request_token
redirect_to request_token.authorize_url #=> "https://api.twitter.com/oauth/authorize?oauth_token=XYZ"
end
def callback
request_token = session[:twitter_request_token]
access_token = request_token.get_access_token(:oauth_verifier => params[:oauth_verifier])
client = Twitter::REST::Client.new(
:consumer_key => CONSUMER_KEY,
:consumer_secret => CONSUMER_SECRET,
:access_token => access_token.token,
:access_token_secret => access_token.secret
)
twitter_user = client.user
redirect_to root_url # or do something with the twitter_user
end
See also: http://barkingiguana.com/2009/10/13/twitter-oauth-authentication-using-ruby/
yes there is the Omniauth gem for authentication with Twitter. The documentation is straight forward.
I personally use Omniauth integrated with Devise and the Twitter gem to access Twitter - works very well.
Hope this helps,
Eugen
The common procedure is the following:
You shell to register your app on twitter development page.
Then set the proper Name, Description, and Website values up for your application.
App Name
App Description
http://your_app_domain.zone:3000/
Change Application Type is your app, by default it has read only access type.
Setup the callback URL for yuor application:
http://your_app_domain.zone:3000/auth/twitter/callback
Store the all keys, and secrets that are shewn on the OAuth tool twitter page:
Consumer key:
Consumer secret:
Access token:
Access token secret:
Setup route on your site with devise, or devise-like gem with the specified twitter keys, and secrets to enable authentication engine. The route list now shall include /auth/twitter path.
By going to http://your_app_domain.zone:3000/auth/twitter you will be redirected to twitter site, and dropped back to your site with passed oauth_token
But
You simple receive those keys, and secrets, and apply then in your app, avoiding the 6, and 7 points:
client = Twitter::REST::Client.new do |config|
config.consumer_key = "YOUR_CONSUMER_KEY"
config.consumer_secret = "YOUR_CONSUMER_SECRET"
config.access_token = "YOUR_ACCESS_TOKEN"
config.access_token_secret = "YOUR_ACCESS_SECRET"
end

Instagram.get_access_token returns BadRequest

I'm trying to authenticate a user with Instagram gem. So I have a page with code param returned by instagram, and I only need to send it back with POST request. According to gem documentation I need to do something like:
get "/oauth/callback" do
response = Instagram.get_access_token(params[:code], :redirect_uri => CALLBACK_URL)
session[:access_token] = response.access_token
redirect "/feed"
end
so I have
def authenticate
response = Instagram.get_access_token(params[:code], :redirect_uri => "http://127.0.0.1:3000")
session[:access_token] = response.access_token
redirect "/feed"
end
And I'm getting
Completed 500 Internal Server Error in 957ms
Instagram::BadRequest (POST https://api.instagram.com/oauth/access_token/: 400):
app/controllers/instagram_controller.rb:25:in `authenticate'
I tried making curl request as per Instagram api documentation, and it works with the same params.
About client_id, I store those keys in instagram.rb in initializers, so it looks like
require "instagram"
Instagram.configure do |config|
config.client_id = "123345"
config.client_secret = "123123"
end
CALLBACK_URL = "http://127.0.0.1:3000"
Thanks a lot in advance.
Found the problem. So, I have devise in my app as well, and I didn't put "redirect_url" in config.omniauth over there. Exactly the same thing people talking about over here https://github.com/Instagram/instagram-ruby-gem/issues/22.
Thanks for help.

How do I use GET and POST on Github using access tokens?

I am using OmniAuth to authenticate a user via Github. OmniAuth provides access tokens. Now I want to send the GET or POST request to Github. I don't want to use any gems, I want to do with Net::HTTP. I did it like this:
<%consumer = OAuth::Consumer.new("mshsD0jpgcYwwOEcTW5ZTA", "V6KTqllY5jS392pj4FNFCb5EiOM8DaFzVwr9cS54XQ", { :site => "https://api.github.com", :request_token_path => '/oauth/request_token', :access_token_path => '/oauth/access_token', :authorize_path => '/oauth/authorize', :scheme => :header })%>
<%access_token = OAuth::AccessToken.new(consumer,auth.token,auth.secret)%>
The same I previously did for Twitter worked fine but now I am getting the following error:
uninitialized constant ActionView::CompiledTemplates::OAuth
Even in the same application the same thing is working for Twitter but not for Github.
I searched through Google but found nothing that helped.
You should be using OAuth2 instead of OAuth. I'd actually recommend using Octokit, it's easy to use and Wynn works for GitHub now so part of his job is keeping it up to date. :)
If you want to use Net::HTTP (although I can't imagine why), you can actually do that without any gems. Just put the token you got from OmniAuth in the request's "Authentication" header.
require 'net/https'
require 'uri'
uri = uri = URI.parse("https://api.github.com/users/username")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
headers = { "Authentication" => "token" }
request = Net::HTTP::Get.new(uri.request_uri, headers)
response = http.request(request)
response.body # => A string containing the JSON response
Seeing as you're already using Omniauth and are familiar with it, I'd recommend using the omniauth-github strategy: https://github.com/intridea/omniauth-github

Resources