Get Auth0 access token via command line - oauth-2.0

I am force to use an unergonomic web site (let’s call it zzz) that uses auth0 for authentication, and a REST API internally, and I have a strong desire to use the API directly.
Using the browser inspector, I can see how that API works, and if I use the JWT Access Token (transmitted using Authorization: Bearer) that I find there, I can script access to API.
The problem I am facing is getting such a JWT access token via auth0, given my username and password.
When I use the browser-based login, I see that zzz redirects me to
https://zzz.eu.auth0.com/login
?state=g6…mo
&client=uz…6j
&protocol=oauth2
&response_type=token%20id_token
&redirect_uri=https%3A%2F%2Ffoo.zzz.com%2Fcallback
&scope=openid%20read%3Amore%20scopes…
&audience=zz-api-prod
&nonce=0G…L7
&auth0Client=ey…n0%3D
(line breaks for your convenience)
I can now manually enter username and password, and get logged in, which seems to perform these steps:
A POST to
https://zzz.eu.auth0.com/usernamepassword/login
with a body of
{ "client_id":"uz…6j",
"redirect_uri":"https://foo.zzz.com/callback",
"tenant":"zzz",
"response_type":"token id_token"
"connection":"zzz-production-users",
"username":"…",
"password":"…",
"nonce":"0G…L7",
"state":"g6…mo",
"sso":true,
"_intstate":"deprecated",
"_csrf":"fb…KI",
"audience":"zzz-api-prod",
"auth0Client":"ey…n0=",
"scope":"openid read:stores more:scopes …",
"protocol":"oauth2"
}
and a response of
<form method="post" name="hiddenform" action="https://zzz.eu.auth0.com/login/callback">
<input type="hidden" name="wa" value="wsignin1.0">
<input type="hidden"
name="wresult"
value="ey…tE">
<input type="hidden" name="wctx" value="…">
<noscript>
<p>
Script is disabled. Click Submit to continue.
</p><input type="submit" value="Submit">
</noscript>
</form>
The JS on the login page seems to press that submit button, causing a POST to
https://zzz.eu.auth0.com/login/callback
which redirects to
https://foo.zzz.com/callback
#access_token=ey…7Q
&scope=openid%20read%3Amore%20scopes…
&expires_in=7200
&token_type=Bearer
&state=%7B%7D
&id_token=ey…Sg
… which contains the precious access token that I want.
Trying to script this precise flow, which would involve parsing the returned HTML to extract the wctx and wresult arguments, is quite tedious.
So my question is:
Is there a way to get the access_token some other way that is more convenient to script using just command line curl, or maybe some simple python code/library?
I have tried various things that I found on the auth0 documentation website (e.g. https://auth0.com/docs/api-auth/tutorials/password-grant#realm-support), but could not get them to work; presmably because they need to be explicitly enabled by zzz in their auth0 settings?

The correct approach should be a separation between these:
Unergonomic web site (Client A) - which uses the implicit flow
Web API
Client B (your command line) - which uses a different flow
In Auth0 you should configure a new OAuth Client Entry for Client B, which should probably use a different flow - perhaps the password grant you mention.
You will at least be able to get a token in this manner. Whether the API accepts calls from you may depend on other design aspects.

Related

Quickbooks Online - How to implement SSO with intuit in Ruby/Rails

I was able to connect with to Intuit using the Minimul/QboApi gem and get the "Connect to Quickbooks" button working with oauth2 based on the example provided on Github. However neither the gem nor the samples show how to implement single sign on with Intuit. In the example provided by Minimul, the Connect To Quickbooks button is produced by intuit's javascript found at https://appcenter.intuit.com/Content/IA/intuit.ipp.anywhere-1.3.5.js
and a setup script and the tag . The tag appears to have been deprecated. Or at least, it doesn't appear to do anything other than produce the button with the right text and logo on it.
But bottom line, I have been unable to find any documentation on the ipp.anywhere.js package, and not even sure if i's meant to used with oauth2 since it's not mentioned anywhere. I believe that the connect to intuit button does the right things, but the guidelines seem pretty strict about what that the button needs to say the right thing and have th eright logo or they will reject it in the store. They also seem to suggest that users are much more likely to try something if an SSO with Intuit workflow is enabled. Any help appreciated.
After some further work, I figured out a solution that can create a 'log in with Inuit button' , although it's a bit of a javascript hack. First, I determined that the only thing I really needed to change was the button image. In other respects the code behind ` works fine for either a "login with intuit" or "connect to intuit work flow" . The only problem is the button image.
Here is the code (adapted from Minimul/QboApi) to get access and oauth2 refresh tokens via a "Connect to Quickbooks" button.
Setup in the controller code in login or sessions controller:
def new
#app_center = QboApi::APP_CENTER_BASE # "https://appcenter.intuit.com"
state= SecureRandom.uuid.to_s
intuit_id = ENV["CLIENT_ID"]
intuit_secret = ENV["CLIENT_SECRET"]
client = Rack::OAuth2::Client.new(
identifier: intuit_id,
secret: intuit_secret,
redirect_uri: ENV["OAUTH_REDIRECT_URL"],
uthorization_endpoint:"https://appcenter.intuit.com/connect/oauth2",
token_endpoint: "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer",
response_type: "code"
)
#make sure to include at least "openid profile email"
#in the scope to you can retrieve user info.
#uri = client.authorization_uri(scope: 'com.intuit.quickbooks.accounting openid profile email phone address', state: state)
end
Here is the code required to generate the button on the view. (The view needs to load jquery as well in order for the script to work.)
<script type="text/javascript" src="<%= #app_center %>/Content/IA/intuit.ipp.anywhere-1.3.5.js">
</script>
<script>
intuit.ipp.anywhere.setup({
grantUrl: "<%== #uri %>",
datasources: {
quickbooks: true,
payments: false
}
});
</script>
<div>
<ipp:connecttointuit></ipp:connecttointuit>
This code produces the following html on the page delivered to the client:
<ipp:connecttointuit>
Connect with QuickBooks
</ipp:connecttointuit>
This code produces a button with the Connect with QuickBooks image, and an event handler inside intuit.ipp.anywhere-1.3.5.js attaches itself to the click event.
The problem is that the button is styled by the class=intuitPlatformConnectButton attribute inside the generated <a> tag, so if you want a "login with intuit button instead of a connect with intuit button the class on the anchor needs to be changed to class='intuitPlatformLoginButtonHorizontal' but still needs to attach to the event handler defined for <ipp:connecttointuit>. The best solution that doesn't require mucking with intuit.ipp.anywhere is to create the connect button and hide it, and then create another tag styled with class=intuitPlatformLoginButtonHorizontal whose click event calls click on the hidden connect button. I use AngularJs on my login page, so I handle the click with ng-click, but it could be done simply with jquery alone.
new.html.erb:
<div>
</div>
<div>
<ipp:connecttointuit id="connectToIntuit" ng-hide="true">< </ipp:connecttointuit>
</div>
and the controller code:
$scope.intuit_login = function() {
let el = angular.element("#connectToIntuit:first-child")
el[0].firstChild.click();
}
This will result in a redirect upon authentication to the supplied redirect url, where you can use openid to get the user credentials.

What is a good returnURL

I am trying to find an example of a good "returnURL" to be used with the Microsoft-Graph-UWP-Connect-SDK example in github.
<Application.Resources>
<!-- Add your client id here. -->
<x:String x:Key="ida:ClientID">xxxxx</x:String>
<x:String x:Key="ida:ReturnUrl">???????</x:String>
</Application.Resources>
I've tried using the Application Registration Portal, but I cannot find the correct entry or results.
Return URIs are the addresses that are allowed to be redirected on to pass the token/codes after authentication. From this example, I’ll use a Raspberry in a UWP. The name will be “laurellerpitest” and will return to port 81 on page token. So http://laurellerpitest:81/token
Important: Do give a read to Getting the access token on the same page.
And see if this works,
<Application.Resources>
<!-- Add your client id here. -->
<x:String x:Key="ida:ClientID">ENTER_YOUR_CLIENT_ID</x:String>
<x:String x:Key="ida:ReturnUrl">`http://laurellerpitest:81/token</x:String>
</Application.Resources>

Kentor MVC Logout don't call logout url

I've an issue on this feature.
SignIn action works well with ADFS and return to AuthServices/Acs
But Logout action don't call ADFS and redirect directly to returnUrl parameters (checked it with fiddler).
I'm calling this link : /AuthServices/Logout?ReturnUrl=~/&Status=LoggedOut
web.config is set up as this :
<kentor.authServices entityId="https://localhost:2181/AuthServices" returnUrl="https://localhost:2181/">
<identityProviders>
<add
entityId="https://ADFS DOMAIN/adfs/services/trust"
signOnUrl="https://ADFS DOMAIN/adfs/ls"
logoutUrl="https://ADFS DOMAIN/adfs/ls/?wa=wsignout1.0"
binding="HttpPost"
allowUnsolicitedAuthnResponse="true"
metadataLocation="https://ADFS DOMAIN/FederationMetadata/2007-06/FederationMetadata.xml"
wantAuthnRequestsSigned="true">
<signingCertificate fileName="~/App_Data/*****.cer" />
</add>
</identityProviders>
</kentor.authServices>
If I launch https://ADFS DOMAIN/adfs/ls/?wa=wsignout1.0 on another tabs, it is working, I return on signin page from my website.
So it seems to be an internal issue to retrieve logouturl and send it ?
Thanks for helps.
There are a number of requirements that need to be met before logout request will be issued:
You need to have a http://kentor.se/AuthServices/LogoutNameIdentifier claim and its issuer has to match the IDP that you're trying to logout from.
You need to have http://kentor.se/AuthServices/SessionIndex claim.
Your AuthServices IDP configuration needs a logoutUrl (I see you've specified this but probably it's easier to let AuthServices read it from the metadata)
You have specified a ServiceCertificate with either Signing or Both usage (i.e. not just Encryption)
Your AuthServices IDP configuration has DisableOutboundLogoutRequests =
false (this is the default)
Missing claims (first two points) is the most likely issue if you have some claims transformation happening during login or you are not retaining the original ClaimsIdentity. See also the documentation regarding ClaimsAuthenticationManager, e.g. https://github.com/KentorIT/authservices/blob/master/doc/ClaimsAuthenticationManager.md
You can turn on logging and see which of these points are failing:
https://github.com/KentorIT/authservices/blob/v0.21.2/Kentor.AuthServices/WebSSO/LogOutCommand.cs#L155-L170

What's the makeup of my access token from Google?

I've acquired the following access token through Google OAuth Playground.
ya29.Ci9aA2EirNhY3InpsLC2Q5ct1XZh2UL60oWWVmkMCBBUL0M-4oAAoigZCJ6O_a4geA
It does not appear to be a JWT (or JWS/JWE for that matter), because I would expect something like 3 segments. The first segment also seems too short to encode the token type.
I know the token must be legitimate, but I cannot for the life of me figure out what specification describes what I'm looking at.
What format is this thing?
The OAuth 2.0 specification says that:
An access token is a string representing an authorization issued to the client. The string is usually opaque to the client.
That is, you should generally not expect to know the format or get any other useful information out of the token.
Of course, it's certainly possible for Google to use JWT or some other container format for the token, but I don't see any indication that that's the case. (This answer also makes me think that they're not in any specified format.)
How exactly are you obtaining that token?
Using the Google's Sign-In button template to initialize the login & grant of permissions process like so gives me a JWT (the idToken):
<meta name="google-signin-client_id" content="{{ OAUTH2_CLIENT_ID }}">
<script src="https://apis.google.com/js/platform.js?onload=onLoad" async defer></script>
<div id="google-signin-button"
class="g-signin2"
data-width="170"
data-height="30"
data-onsuccess="onSignIn"
data-onfailure="onSignInFailure">
</div>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var idToken = googleUser.getAuthResponse().id_token;
}

Best way to upload files to Box.com programmatically

I've read the whole Box.com developers api guide and spent hours on the web researching this particular question but I can't seem to find a definitive answer and I don't want to start creating a solution if I'm going down the wrong path. We have a production environment where as once we are finished working with files our production software system zips them up and saves them into a local server directory for archival purposes. This local path cannot be changed. My question is how can I programmatically upload these files to our Box.com account so we can archive these on the cloud? Everything I've read regarding this involves using OAuth2 to gain access to our account which I understand but it also requires the user to login. Since this is an internal process that is NOT exposed to outside users I want to be able to automate this otherwise it would not be feasable for us. I have no issues creating the programs to trigger everytime a new files gets saved all I need is to streamline the Box.com access.
I just went through the exact same set of questions and found out that currently you CANNOT bypass the OAuth process. However, their refresh token is now valid for 60 days which should make any custom setup a bit more sturdy. I still think, though, that having to use OAuth for an Enterprise setup is a very brittle implementation -- for the exact reason you stated: it's not feasible for some middleware application to have to rely on an OAuth authentication process.
My Solution:
Here's what I came up with. The following are the same steps as outlined in various box API docs and videos:
use this URL https://www.box.com/api/oauth2/authorize?response_type=code&client_id=[YOUR_CLIENT_ID]&state=[box-generated_state_security_token]
(go to https://developers.box.com/oauth/ to find the original one)
paste that URL into the browser and GO
authenticate and grant access
grab the resulting URL: http://0.0.0.0/?state=[box-generated_state_security_token]&code=[SOME_CODE]
and note the "code=" value.
open POSTMAN or Fiddler (or some other HTTP sniffer) and enter the following:
URL: https://www.box.com/api/oauth2/token
create URL encoded post data:
grant_type=authorization_code
client_id=[YOUR CLIENT ID]
client_secret=[YOUR CLIENT SECRET]
code= < enter the code from step 4 >
send the request and retrieve the resulting JSON data:
{
"access_token": "[YOUR SHINY NEW ACCESS TOKEN]",
"expires_in": 4255,
"restricted_to": [],
"refresh_token": "[YOUR HELPFUL REFRESH TOKEN]",
"token_type": "bearer"
}
In my application I save both auth token and refresh token in a format where I can easily go and replace them if something goes awry down the road. Then, I check my authentication each time I call into the API. If I get an authorization exception back I refresh my token programmatically, which you can do! Using the BoxApi.V2 .NET SDK this happens like so:
var authenticator = new TokenProvider(_clientId, _clientSecret);
// calling the 'RefreshAccessToken' method in the SDK
var newAuthToken = authenticator.RefreshAccessToken([YOUR EXISTING REFRESH TOKEN]);
// write the new token back to my data store.
Save(newAuthToken);
Hope this helped!
If I understand correctly you want the entire process to be automated so it would not require a user login (i.e run a script and the file is uploaded).
Well, it is possible. I am a rookie developer so excuse me if I'm not using the correct terms.
Anyway, this can be accomplished by using cURL.
First you need to define some variables, your user credentials (username and password), your client id and client secret given by Box (found in your app), your redirect URI and state (used for extra safety if I understand correctly).
The oAuth2.0 is a 4 step authentication process and you're going to need to go through each step individually.
The first step would be setting a curl instance:
curl_setopt_array($curl, array(
CURLOPT_URL => "https://app.box.com/api/oauth2/authorize",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "content-type: application/x-www-form-urlencoded",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>
"response_type=code&client_id=".$CLIENT_ID."&state=".$STATE,
));
This will return an html text with a request token, you will need it for the next step so I would save the entire output to a variable and grep the tag with the request token (the tag has a "name" = "request_token" and a "value" which is the actual token).
Next step you will need to send another curl request to the same url, this time the post fields should include the request token, user name and password as follows:
CURLOPT_POSTFIELDS => "response_type=code&client_id=".$CLIENT_ID."&state=".$STATE."&request_token=".$REQ_TOKEN."&login=".$USER_LOGIN."&password=".$PASSWORD
At this point you should also set a cookie file:
CURLOPT_COOKIEFILE => $COOKIE, (where $COOKIE is the path to the cookie file)
This will return another html text output, use the same method to grep the token which has the name "ic".
For the next step you're going to need to send a post request to the same url. It should include the postfields:
response_type=code&client_id=".$CLIENT_ID."&state=".$STATE."&redirect_uri=".$REDIRECT_URI."&doconsent=doconsent&scope=root_readwrite&ic=".$IC
Be sure to set the curl request to use the cookie file you set earlier like this:
CURLOPT_COOKIEFILE => $COOKIE,
and include the header in the request:
CURLOPT_HEADER => true,
At step (if done by browser) you will be redirected to a URL which looks as described above:
http://0.0.0.0(*redirect uri*)/?state=[box-generated_state_security_token]&code=[SOME_CODE] and note the "code=" value.
Grab the value of "code".
Final step!
send a new cur request to https//app.box.com/api/oauth2/token
This should include fields:
CURLOPT_POSTFIELDS => "grant_type=authorization_code&code=".$CODE."&client_id=".$CLIENT_ID."&client_secret=".$CLIENT_SECRET,
This will return a string containing "access token", "Expiration" and "Refresh token".
These are the tokens needed for the upload.
read about the use of them here:
https://box-content.readme.io/reference#upload-a-file
Hope this is somewhat helpful.
P.S,
I separated the https on purpuse (Stackoverflow wont let me post an answer with more than 1 url :D)
this is for PHP cURL. It is also possible to do the same using Bash cURL.
For anyone looking into this recently, the best way to do this is to create a Limited Access App in Box.
This will let you create an access token which you can use for server to server communication. It's simple to then upload a file (example in NodeJS):
import box from "box-node-sdk";
import fs from "fs";
(async function (){
const client = box.getBasicClient(YOUR_ACCESS_TOKEN);
await client.files.uploadFile(BOX_FOLDER_ID, FILE_NAME, fs.createReadStream(LOCAL_FILE_PATH));
})();
Have you thought about creating a box 'integration' user for this particular purpose. It seems like uploads have to be made with a Box account. It sounds like you are trying to do an anonymous upload. I think box, like most services, including stackoverflow don't want anonymous uploads.
You could create a system user. Go do the Oauth2 dance and store just the refresh token somewhere safe. Then as the first step of your script waking up go use the refresh token and store the new refresh token. Then upload all your files.

Resources