Saml_IDP gem not pulling metadata or acceptable_hosts - ruby-on-rails

I'm trying to implement SSO via SAML and using my application as both the IdP (routes are based off localhost:3000) and SP (routes based off lvh.me:3000). I used the saml_idp gem to set up the IdP and the omniauth-saml gem for the SP side.
I can get a request sent to the IdP and a response sent back if I bypass the validate_saml_request method in the SamlIdpController in the gem. The response I get returns the user's email and first/last name per what I configured in the config/saml_idp.rb file.
I really don't want to bypass the validate_saml_request. When I looked to see why my request is not being validated, I see that the logs return '[] compare to lvh.me' and 'No acceptable AssertionConsumerServiceURL, either configure them via config.service_provider.response_hosts or match to your metadata_url_host'.
For SPs, my config/saml_idp.rb file looks like:
service_providers = {
"my-application" => {
fingerprint: ENV['SAML_CERT_FINGERPRINT'],
metadata_url: "http://lvh.me:3000/auth/saml/metadata",
response_hosts: ["lvh.me:3000"]
},
}
I confirmed that the metadata does exist at that metadata_url as well. Not really sure why it's not pulling anything via the metadata_url or response_hosts via the config.
On my SP side, the config/omniauth.rb file looks like:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :saml,
:assertion_consumer_service_url => "http://lvh.me:3000/auth/saml/callback",
:issuer => "portal",
:idp_sso_target_url => "http://localhost:3000/saml/auth",
:idp_sso_target_url_runtime_params => {:original_request_param => :mapped_idp_param},
:idp_cert => ENV['SAML_CERT'],
:idp_cert_fingerprint => ENV['SAML_CERT_FINGERPRINT'],
:idp_cert_fingerprint_validator => lambda { |fingerprint| fingerprint },
:name_identifier_format => "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"
end

While I was unable to get it working using this piece of configuration in the config/saml_idp.rb file, I only needed to have the IdP interact with one SP and was able to get it working by adjusting what I passed to response_hosts and using another part of the code given in the config file (example below):
config.service_provider.finder = ->(issuer_or_entity_id) do
{
fingerprint: ENV['SAML_CERT_FINGERPRINT'],
metadata_url: "http://lvh.me:3000/saml/metadata",
response_hosts: ["lvh.me"]
}
end

Related

Can't get OAuth 2 Scope. It is not set. Quickbook

I have successfully integrated Quickbook accounting APIs with the Development Keys and Credentials. Moreover, when I put Production Keys and Secret, I got an error with status code (403), and later I got to know that is because of scopes.
I noticed there is a function called "getScope()" to check the token scopes. I went to try that and get the following error:
Can't get OAuth 2 Scope. It is not set.
I even tried using access and refresh tokens from the API playground. Still, the error is there.
Here is my code snippet:
$dataService = DataService::Configure(array(
'auth_mode' => 'oauth2',
'ClientID' => $quickBookData->client_id,
'ClientSecret' => $quickBookData->client_secret,
'accessTokenKey' => $quickBookData->access_token,
'refreshTokenKey' => $quickBookData->refresh_token,
'QBORealmID' => $quickBookData->realm_id,
'baseUrl' => "production",
));
$OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
$scopes = $OAuth2LoginHelper->getScope();

Rails - gem instagram - issues on access token and sandbox

I need to put on a website the complete instagram feed of my customer. I have tried several ways to access to instagram and get the whole feed, but I get some errors.
Using the gem "instagram" (the easiest and simplest method) i got the following error when I try to get the access token.
Instagram::BadRequest: POST https://api.instagram.com/oauth/access_token/: 400: OAuthException: Matching code was not found or was already used.
I tried to follow the indication on the instagram documentation https://www.instagram.com/developer/authentication/ using my browser and I can get the access token, but I am not able to do the http calls manually in ruby.
I need to download all the data and keep it inside my database (as I always done) so I need everything in the controller.
my code is very simple:
accessToken = Instagram.get_access_token(Instagram.client_id, :redirect_uri => CALLBACK_URL)
client = Instagram.client(access_token: accessToken)
response = client.user_recent_media
#other code to cycle inside posts and put everything in db
i'm sure to have included the same redirect_url in my instragram registration app and in my code.
As shown in the sample application in the gem's repo, you will need to call authorize_url first:
Instagram.authorize_url(:redirect_uri => CALLBACK_URL)
and then you will get request on the CALLBACK_URL, where you should have an action with the code that you provided:
response = Instagram.get_access_token(params[:code], :redirect_uri => CALLBACK_URL)
client = Instagram.client(:access_token => response.access_token)
# do stuff with the client
SOLVED!
I have misunderstood the usage of the api.
I got my access token following this https://elfsight.com/blog/2016/05/how-to-get-instagram-access-token/
and i can access my posts using in my model:
access_token = Instagram.access_token
client = Instagram.client(access_token: access_token)
response = client.user_recent_media
and in my config file:
Instagram.configure do |config|
config.client_id = "CLIENT_ID"
config.client_secret = "CLIENT_SECRET"
config.access_token = "ACCESS_TOKEN"
end
thanks a lot for your support
you should get the token when processing the callback in the omniauth.auth hash: request.env['omniauth.auth']['credentials']['token']

Google OAuth 2 redirect_uri_mismatch - OmniAuth Rails app

I've a problem with authenticating Google account with my Rails app.
I'm using omniauth-google-oauth2 gem with Devise.
Always get this Error when I try to access google account:
Error: redirect_uri_mismatch
The redirect URI in the request: http://localhost:3000/users/auth/google_oauth2/callback did not match a registered redirect URI
I'm sure that the registered redirect URI in my google console app is right and identical with requested one, just like that:
so what's main the problem here?
try this way :
add require "omniauth-google-oauth2" to devise.rb in config/initializers folder
add http://localhost:3000/users/auth/google_oauth2/callback into Redirect URL in google API console https://console.developers.google.com
restart server
Mine solution is to force redirect_url in both (code/token) stages, devise.rb initializer:
CALLBACK_URL = 'https://SOMESERVER/users/auth/google_oauth2/callback'
Devise.setup do |config|
config.omniauth :google_oauth2,
"SOMECLIENTID.apps.googleusercontent.com",
"SOMEKEY",
{
:client_options => {:ssl => {:ca_file => 'C:\Ruby21\cacert.pem'}},
:provider_ignores_state => true,
:prompt => "select_account",
:redirect_uri => CALLBACK_URL,
setup: (lambda do |env|
request = Rack::Request.new(env)
env['omniauth.strategy'].options['token_params'] = {:redirect_uri => CALLBACK_URL}
end)
}
end
there is discussion about the issue here: https://github.com/zquestz/omniauth-google-oauth2/issues/181
Be careful of what client id you are setting.
Google API provides two:
Client ID for Google Compute and App Engine
Client ID for web applications
You need to use Client ID for web applications
Make sure you set up the Product Name and Email address via the Consent Screen Link.
Per the omniauth-google-oauth2 documentation you need to:
Go to 'https://console.developers.google.com'
Select your project.
Click 'APIs & auth'
Make sure "Contacts API" and "Google+ API" are on.
Go to Consent Screen, and provide a 'PRODUCT NAME'
Wait 10 minutes for changes to take effect.
I had the same issue, made the updates, waited 10 minutes, still nothing, went to lunch, then it started to work. Guess patience was part of the key to success on this one.

Cannot get oAuth2 Access Token for Google Analytics API

I am using Rails + Garb Gem (Sija Branch) + omniauth-google-oauth2 Gem and I can successfully authenticate with the Google Analytics API and extract data that our app is generating when using a user login, e.g.:
Garb::Session.login('USERNAME', '<PASSWORD>')
I can then use Garb to connect to the Analytics Profile I want and pull the data from it and display some charts on a webpage. This all works fine.
However, I want to use oAuth2 to authenticate with Analytics which is why I had to install the Sija branch of the Garb Gem from Github (it supports oAuth2) and I also installed the omniauth-google-oauth2 Gem. Now in theory I should be able to authenticate using the following code:
Garb::Session.access_token = access_token # an instance of OAuth2::Client
It's at this point that it gets a little hazy for me and I would greatly appreciate some guidance. Here's how far I have gotten:
1) I created a Project in the Google API console and turned on Analytics API under Services
2) This provided me with a Client ID and Client Secret
3) I came across this code which I could populate with the ID and Secret above:
client = OAuth2::Client.new(
GOOGLE_CLIENT_ID,
GOOGLE_CLIENT_SECRET,
{
:site => 'https://accounts.google.com',
:authorize_url => '/o/oauth2/auth',
:token_url => '/o/oauth2/token'
})
4) Then there is the next bit of code:
response = OAuth2::AccessToken.new(
client,
STORED_TOKEN, {
refresh_token: STORED_REFRESH_TOKEN,
expires_at: STORED_EXPIRES_AT
})
5) and then in theory connect with:
Garb::Session.access_token = response
The problem I have is I don't have the token information in Point (4) above. It seems to me that with oAuth2 I need to do a "handshake" once and print out the return token values? Perhaps through Rails code which prints the values returned out and then paste the token values into a constant in the Rails app so that I can use them in the above code? I really am confused. As I mentioned earlier, the web app works fine using the user login authentication. All the web app is doing is authenticating with analytics, pulling down some data and drawing a chart. But I am stuck converting it over to oAuth2 as I just do not know how to get the Access Token that the Garb Gem is looking for. I should also note that this is not a public website with multiple users authenticating, this is a CMS website that is connecting to our own Analytics data.
I have seen some partial snippets of aspects of this but not a fully explained or working example. I would really appreciate any guidance and help with this question.
Many thanks in advance,
JR
I've soldiered through this over the last few weeks, so let me share what worked:
To use Oauth2 you need to get a 'refresh token' that you use to 're-authenticate' with google each time you make an API call. The steps for this are as follows:
1) Setup your account in the API console - https://code.google.com/apis/console/b/0/ (seems like you've done that well)
2) In your API account, make sure you have a redirect URI pointing back to your application:
http://some-url.com/auth/google_oauth2/callback
http://localhost:3000/auth/google_oauth2/callback
Note here that google won't let you call back to your local machine as 0.0.0.0:3000... so you'll need to use localhost explicitly
3) In your route file, tie that redirect url to an action in the controller where you're going to create the project or authentication
match '/auth/:provider/callback' => 'authentications#create'
The ':provider' simply lets you match on multiple types of oauth, but you could just put 'google_oauth2' there as well.
4) Now create that action in your controller
def create
auth = request.env["omniauth.auth"]
params = request.env["omniauth.params"]
project = Project.find(params['project_id'])
Authentication.create(:project_id => project.id, :provider => auth['provider'], :uid => auth['uid'], :access_token => auth['credentials']['refresh_token'])
flash[:notice] = "Authentication successful."
redirect_to owner_view_project_path(project)
end
5) The controller action should retrieve the relevant fields from the response object (details of response object here: https://github.com/zquestz/omniauth-google-oauth2) - in particular, you need to get the 'refresh_token' and save that to your project or authentication object - if you haven't added an 'access_token' attribute to the desired object, go do that now with a migration, then start saving the refresh token to that attribute
6) Now when you're ready to call that particular authentication and get API data for it, you can load up that object where you saved the access token, and use that to get a new session with the google API as follows:
#authentication = Authentications.find(params[:id])
client = OAuth2::Client.new GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET,
{
:site => 'https://accounts.google.com',
:authorize_url => "/o/oauth2/auth",
:token_url => "/o/oauth2/token",
}
response = OAuth2::AccessToken.from_hash(client, :refresh_token => #authentication.access_token).refresh!
Garb::Session.access_token = response
#profiles = Garb::Management::Profile.all
What this code did was create an OAuth2 access token (response) by specifying the client and then a refresh_token, then calling 'refresh!' to get a refreshed access token... then use that access token to establish your Garb session, then call down all the profiles for a given account using the Gard::Management::Profile.all
Hope this helps - let me know if you have questions!
Just a note on what worked for me in:
For steps 3, 4 & 5 I used cURL instead to retrieve the Access/Refresh token. Step 6 is then the same for me (using the Sija branch of the Garb Gem). So using cURL:
Using the details associated with your Google app POST the following using cURL:
curl --data "code=<APP_CODE>&redirect_uri=http://localhost:3000/oauth2callback&client_id=<CLIENT_ID>.apps.googleusercontent.com&scope=&client_secret=<CLIENT_SECRET>&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token
The response takes the form:
{
"access_token" : "<ACCESS_TOKEN>",
"token_type" : "Bearer",
"expires_in" : 3600,
"refresh_token" : "<REFRESH_TOKEN>"
}
which you can plug into the Garb Gem as per part 6.
The answer by #CamNorgate is valid.
If you don't have a "refresh_token" back from Omniauth on the callback make sure you are correctly initializing :google_oauth2
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"],
{ :scope=>"https://www.google.com/m8/feeds, https://www.googleapis.com/auth/userinfo.email, https://www.googleapis.com/auth/userinfo.profile",
:approval_prompt=>"force", access_type="offline"
}
end
Make sure to include :approval_prompt=>"force", access_type="offline" in order for the refresh_token to be sent back. The refresh_token is only provided on the first authorization from the user.

Google-api-client asking for access token

My requirement is to get top 20 links for a search query in google.com.
I am using the Google-api-client! for ruby.
Here goes the code I am using,
require 'google/api_client'
client = Google::APIClient.new
response = client.execute(
search.cse.list, 'key' => '<My Key>', 'cx' => '013036536707430787589%3A_pqjad5hr1a', 'alt' => 'json', 'q' => 'hello world'
)
Now I am facing three problems,
I want to use default Google search, so what should be the 'cx' value? One which I used, is from https://developers.google.com/custom-search/v1/using_rest#cx
I am getting no results, instead getting the following warning "ArgumentError: Missing access token." I solved this issue using a dummy token, by defining "client.authorization.access_token = '123'" . But I am not sure, if it is a correct solution or not.
After I define the access_token, still I am getting no result. Instead getting the warning "Invalid Credentials". But if I use the same URL(generated by the api), in the browser I am getting results.
Instead of setting a dummy access token, just set the authorization mechanism to nil:
client.authorization = nil
This way it won't send an authorization header and will just rely on the API key for identifying your app.

Resources