When I send any message it gives an error.
Twilio::REST::RequestError: The requested resource /2010-04-01/Accounts/cafac01e41ad5fbad3da4ad8619c8d36/Messages.json was not found
# set up a client to talk to the Twilio REST API
#client = Twilio::REST::Client.new account_sid, auth_token
#client.account.messages.create({
:from => 'xxxxxx',
:to => 'xxxxxx',
:body => 'Twilio Testing',
})
Aside from the potential issue Devin brought up in the comments regarding an incorrect Account SID in your Url, the following code examples may help.
Code to setup Twilio-Ruby:
require 'rubygems' # not necessary with ruby 1.9 but included for completeness
require 'twilio-ruby'
# put your own credentials here
account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
auth_token = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy'
# set up a client to talk to the Twilio REST API
#client = Twilio::REST::Client.new account_sid, auth_token
# alternatively, you can preconfigure the client like so
Twilio.configure do |config|
config.account_sid = account_sid
config.auth_token = auth_token
end
# and then you can create a new client without parameters
#client = Twilio::REST::Client.new
And then the code to send an SMS:
#client.messages.create(
from: '+1415XXXXXXX',
to: '+1610XXXXXXX',
body: 'Hey there!'
)
Related
I spent hours looking for a solution to my problem without luck.
I created a Rails app that interacts with Google Calendar API and, following a guide, I was able to make it work. Then I shut down my local server and ran it again after 2/3 hours and I started receiving this error when I make a request to the API:
Signet::AuthorizationError (Unexpected error: #<ArgumentError: Missing authorization code.>)
I figured out that the problem is that the token is expired, 'cause I can't understand why it was working and then not anymore.
This is my controller:
require 'google/api_client/client_secrets.rb'
require 'google/apis/calendar_v3'
CALENDAR_ID = Here I have my Calendar_ID
GOOGLE_CLIENT_ID = Here I have my Google_Client_ID
GOOGLE_CLIENT_SECRET = Here I have my Google_Client_Secret
class CalendarController < ApplicationController
def calendars
client = Signet::OAuth2::Client.new(client_options)
client.update!(session[:authorization])
service = Google::Apis::CalendarV3::CalendarService.new
service.authorization = client
#calendar_list = service.list_calendar_lists
rescue Google::Apis::AuthorizationError
response = client.refresh!
session[:authorization] = session[:authorization].merge(response)
retry
end
def redirect
client = Signet::OAuth2::Client.new(client_options)
redirect_to client.authorization_uri.to_s, allow_other_host: true
end
def callback
client = Signet::OAuth2::Client.new(client_options)
client.code = params[:code]
response = client.fetch_access_token!
session[:authorization] = response
redirect_to calendars_url
end
private
def client_options
{
client_id: GOOGLE_CLIENT_ID,
client_secret: GOOGLE_CLIENT_SECRET,
authorization_uri: 'https://accounts.google.com/o/oauth2/auth',
token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
scope: Google::Apis::CalendarV3::AUTH_CALENDAR,
redirect_uri: callback_url
}
end
end
Then my routes:
get '/redirect', to: 'calendar#redirect', as: 'redirect'
get '/callback', to: 'calendar#callback', as: 'callback'
get '/calendars', to: 'calendar#calendars', as: 'calendars'
What can I do to solve my issue? I'm a newbie on Rails, so it's not quite simple for me
I'm trying to get a html button to redirect to my Azure login page from the homepage.
If I put in my browser localhost/3000/authentication/login it goes to the Azure web app.
This is what I'm trying to achieve with this:
<%= button_to 'Login', authentication_login_path, method: :get %>
My routes file is:
Rails.application.routes.draw do
root 'application#home'
get 'application/home'
get 'authentication/login', to: 'authentication#index'
resources :authentication
end
The Application and Home controllers just have blank functions at the moment.
I've tried rake | grep authentication and it contains the correct path:
authentication_login GET /authentication/login(.:format) authentication#index
Therefore, I'm not sure what doing authentication_login_path is not recognized in my home.html.erg file.
This is the Authentication_Controller. I'm trying to execute the index method as this will begin the authentication process.
require 'oauth2'
class AuthenticationController < ApplicationController
# You need to configure a tenant at Azure Active Directory(AAD) to register web app and web service app
# You will need two entries for these app at the AAD portal
# You will put clientid and clientsecret for your web app here
# ResourceId is the webservice that you registered
# RedirectUri is registered for your web app
CLIENT_ID = '56938f79-a23e-4f3f-a033-d23546d9056f'
CLIENT_SECRET = '5j8Hv8U1x_l-t047OZq9~LmK~kMdobV3rm'
AUTHORITY = 'https://login.windows.net/'
AUTHORIZE_URL = "https://beautytruth.b2clogin.com/beautytruth.onmicrosoft.com/B2C_1_btSignInSignOut/oauth2/v2.0/authorize"
TOKEN_URL = "https://beautytruth.b2clogin.com/beautytruth.onmicrosoft.com/B2C_1_btSignInSignOut/oauth2/v2.0/token"
RESOURCE_ID = '/subscriptions/eb589fa5-ed57-4e10-81c9-32e4284af10c/resourceGroups/btAdvertisingNetwork' #ResourceId or ResourceURI that you registered at Azure Active Directory
REDIRECT_URI = 'http://localhost:3000/welcome/callback'
def index
update_token
if session['access_token']
puts "Auth has been checked"
# show main page and use token
redirect_to
else
# start authorization
client = get_client
a = client.auth_code.authorize_url(:client_id => CLIENT_ID, :resource => RESOURCE_ID, :redirect_uri => REDIRECT_URI)
redirect_to(a)
end
end
def callback
begin
#code = params[:code]
client = get_client
# post token to mobile service api
#token = client.auth_code.get_token(CGI.escape(#code), :redirect_uri => REDIRECT_URI)
# id_token token.params["id_token"]
#multi resource token token.params["resource"]
token = client.auth_code.get_token(#code, :redirect_uri => REDIRECT_URI, )
session['access_token'] = token.token
session['refresh_token'] = token.refresh_token
session['expire_at'] = token.expire_at
session['instance_url'] = token.params['instance_url']
redirect '/'
rescue => exception
output = '<html><body><p>'
output += "Exception: #{exception.message}<br/>"+exception.backtrace.join('<br/>')
output += '</p></body></html>'
end
end
def update_token
puts "update token inside"
token = session['access_token']
refresh_token = session['refresh_token']
expire_at = session['expire_at']
#access_token = OAuth2::AccessToken.from_hash(get_client, { :access_token => token, :refresh_token => refresh_token, :expire_at => expire_at, :header_format => 'Bearer %s' } )
if #access_token.expired?
puts "refresh token"
#access_token = #access_token.refresh!
session['access_token'] = #access_token.token
session['refresh_token'] = #access_token.refresh_token
session['expire_at'] = #access_token.expire_at
session['instance_url'] = #access_token.params['instance_url']
end
end
# send post request to webservice to send token and create a post request
def use_token
# we got the token and now it will posted to the web service in the header
# you can specify additional headers as well
# token is included by default
update_token
conn = Faraday.new(:url => 'https://btadvertisingplatform.azurewebsites.net/') do |faraday|
faraday.request :url_encoded # form-encode POST params
faraday.response :logger # log requests to STDOUT
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
response = conn.get do |req|
req.url '/api/WorkItem'
req.headers['Content-Type'] = 'application/json'
req.headers['Authorization'] = 'Bearer '+#access_token.token
end
#out = response.body
end
def get_client
client = OAuth2::Client.new(CLIENT_ID, CLIENT_SECRET, :site => AUTHORITY, :authorize_url => AUTHORIZE_URL, :token_url => TOKEN_URL )
client
end
end
As you already have resource :authentication you can use the following.
<%= button_to 'Login', authentication_index_path, method: :get %>
You don't need an additional route. You can remove the following route
get 'authentication/login', to: 'authentication#index'
I am developing a Rails 4 web application and i am planning to authenticate a user from my Windows Azure AD.
For that i have subscribed to Windows Azure and created Active Directory. I then created an application inside AD to get Client and Secret ID to access API exposed by windows Azure from my Rails web application.
For this i am planning to use Devise gem . Is this the right solution or is there any other libraries available to achieve this.
Any help is appreciated.
Not sure if you're still looking for anything, but this Gist has the requisite request code using the OAuth2 gem. If you were ultimately able to get things working with another means (Devise, etc.), I'd also be interested to know what you did.
Here's the code from the Gist as packaged into a controller by omercs:
require 'oauth2'
class WelcomeController < ApplicationController
# You need to configure a tenant at Azure Active Directory(AAD) to register web app and web service app
# You will need two entries for these app at the AAD portal
# You will put clientid and clientsecret for your web app here
# ResourceId is the webservice that you registered
# RedirectUri is registered for your web app
CLIENT_ID = 'b6a42...'
CLIENT_SECRET = 'TSbx..'
AUTHORITY = 'https://login.windows.net/'
AUTHORIZE_URL = "/yourtenant.onmicrosoft.com/oauth2/authorize"
TOKEN_URL = "/yourtenant.onmicrosoft.com/oauth2/token"
RESOURCE_ID = 'https://yourtenant.onmicrosoft.com/AllHandsTry' #ResourceId or ResourceURI that you registered at Azure Active Directory
REDIRECT_URI = 'http://localhost:3000/welcome/callback'
def index
update_token
if session['access_token']
# show main page and use token
redirect_to welcome_use_token_path
else
# start authorization
client = get_client
a = client.auth_code.authorize_url(:client_id => CLIENT_ID, :resource => RESOURCE_ID, :redirect_uri => REDIRECT_URI)
redirect_to(a)
end
end
def callback
begin
#code = params[:code]
client = get_client
# post token to mobile service api
#token = client.auth_code.get_token(CGI.escape(#code), :redirect_uri => REDIRECT_URI)
# id_token token.params["id_token"]
#multi resource token token.params["resource"]
token = client.auth_code.get_token(#code, :redirect_uri => REDIRECT_URI, )
session['access_token'] = token.token
session['refresh_token'] = token.refresh_token
session['expire_at'] = token.expire_at
session['instance_url'] = token.params['instance_url']
redirect '/'
rescue => exception
output = '<html><body><p>'
output += "Exception: #{exception.message}<br/>"+exception.backtrace.join('<br/>')
output += '</p></body></html>'
end
end
def update_token
puts "update token inside"
token = session['access_token']
refresh_token = session['refresh_token']
expire_at = session['expire_at']
#access_token = OAuth2::AccessToken.from_hash(get_client, { :access_token => token, :refresh_token => refresh_token, :expire_at => expire_at, :header_format => 'Bearer %s' } )
if #access_token.expired?
puts "refresh token"
#access_token = #access_token.refresh!;
session['access_token'] = #access_token.token
session['refresh_token'] = #access_token.refresh_token
session['expire_at'] = #access_token.expire_at
session['instance_url'] = #access_token.params['instance_url']
end
end
# send post request to webservice to send token and create a post request
def use_token
# we got the token and now it will posted to the web service in the header
# you can specify additional headers as well
# token is included by default
update_token
conn = Faraday.new(:url => 'https://yoursite.azurewebsites.net/') do |faraday|
faraday.request :url_encoded # form-encode POST params
faraday.response :logger # log requests to STDOUT
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
response = conn.get do |req|
req.url '/api/WorkItem'
req.headers['Content-Type'] = 'application/json'
req.headers['Authorization'] = 'Bearer '+#access_token.token
end
#out = response.body
end
def get_client
client = OAuth2::Client.new(CLIENT_ID, CLIENT_SECRET, :site => AUTHORITY, :authorize_url => AUTHORIZE_URL, :token_url => TOKEN_URL )
client
end
end
I want to write a script which calls a REST API using a URL like:
http://localhost:3000/api/v1/user/xyz
If I open this URL in the browser, it asks for a user email and password. Once I've authenticated, it returns a JSON response with a user id. I don't know how I should I authenticate through the script. Can someone give me a suggestion?
This is what I started with:
require 'rubygems'
require 'net/http'
require 'json'
api_url = "http://localhost:3000/api/v1//user/xyz"
response = Net::HTTP.get_response(URI.parse(api_url))
data = JSON.parse(response.body)
fields = data.keys
puts fileds
puts data.keys
This is the authentication for the API:
before_filter :authorize, :except => [:keys]
private
def authorize
authenticate_or_request_with_http_basic do |username, password|
user = User.find_by_email(username)
if user && user.valid_password?(password)
sign_in :user, user
end
end
end
How I can pass email and password to authenticate this API so I can get "id" as return?
rest_client gem works great for me. As far as what the API returns that should be in the documentation. You can always try it in IRB and see what the response contains.
HTTP Basic authentication is pretty simple to add to your request, though I don't think you can use the get_response convenience method.
See: http://ruby-doc.org/stdlib-2.0/libdoc/net/http/rdoc/Net/HTTP.html#label-Basic+Authentication
Example from the documentation:
uri = URI('http://example.com/index.html?key=value')
req = Net::HTTP::Get.new(uri)
req.basic_auth 'user', 'pass' # username, password go here.
res = Net::HTTP.start(uri.hostname, uri.port) {|http|
http.request(req)
}
puts res.body
I'm trying to grab Twilio recordings with the following GET request to their API in my Rails controller:
def myrecordings
account_sid = 'AC32a3c49700934481addd5ce1659f04d2'
auth_token = 'asd89f677asd897asdfd9' #this is made up for now
client = Twilio::REST::Client.new(account_sid, auth_token)
#recordings = client.account.recordings.list()
render :json => #recordings
end
As a result I'm getting a 500 response error with the message "Authenticate"
My application trace is
app/controllers/campaigns_controller.rb:13:in `myrecordings' [the #recordings line]
To the best of my knowledge I'm following what are in the Twilio docs here:
http://www.twilio.com/docs/api/rest/recording
But clearly I'm missing something. The account_sid and auth_token are correct, but is there a security issue?
require 'rubygems'
require 'twilio-ruby' # Download twilio-ruby from twilio.com/docs/libraries
# Get your Account Sid and Auth Token from twilio.com/user/account
account_sid = 'AC32a3c49700934481addd5ce1659f04d2'
auth_token = '{{ auth_token }}'
#client = Twilio::REST::Client.new account_sid, auth_token
# Loop over recordings and print out a property for each one
#client.account.recordings.list.each do |recording|
puts recording.sid
end
From the docs, this should work too, assuming you change the sid and token to the right ones