Using the new OAuth 2 in Box - box-api

I'm trying to use the new Box authentication API with OAuth. I would like to use the credential of the the box account I'm currently using to authorize my application.
The configuration of OAuth requests a redirection URI and I don't know what must be entered there. In the previous authentication method, the following URI was given http://www.box.net/api/1.0/auth/{ticket}, but this was done after getting the authentication ticket.
I'm new to OAuth so my question may be a bit obvious... but I'd like to know how to do the authentication with the credentials of a box account user.
I'm doing this in a Windows application, so I would also like to understand how to show the response from the request.

When I was searching around for answers on creating a Box.net application for desktop trying to get the login authentication took more than that it really should have...
So I decided to put together an article on my website that talks through the process of creating a C# .Net 4.0 desktop application that can login and work with their SDK. This is using their new OAuth 2.0 login system.
Firstly we send the initial web request using a standard HttpWebRequest object to get the UI web page for the OAuth 2.0 login. Once the web response has been returned, we convert it into a Stream for our web-browser to consume. The redirect URI can be any HTTPS based URI.
string baseURI = "https://www.box.com/api/oauth2/authorize?";
string responseType = "&response_type=code";
string clientId = "&client_id=YOUR OWN CLIENT ID";
string redirectURI = "&redirect_uri=https://app.box.com/services/poc_connector";
var targetUri = new Uri(baseURI + responseType + clientId + redirectURI);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(targetUri);
To inject the Stream into the web-browser control we use the document property
webBrowser1.DocumentStream = view;
Once that is done all the operations by the user are handled by the web-browser control. To capture the Authentication token when the user presses the "Grant access" button. We add an event listener for the web-browsers Navigated event.
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
if (e.Url.AbsolutePath != "blank" && e.Url.ToString().Contains("&code="))
{
Token = e.Url.ToString().Substring(e.Url.ToString().IndexOf("&code="));
Token = Token.Replace("&code=", String.Empty);
this.Close();
}
}
Link my original article and source code: link

The first step in the OAuth 2 process is sending the user to https://api.box.com/oauth2/authorize with response_type and client_id as parameters of the request. The redirect URL will be the same as what you set in V1. If you client_id was 123456, for example, you could direct the user to
https://api.box.com/oauth2/authorize?response_type=code&client_id=123456
See here for more info.

Related

Receive authentication response data from a non-Google service via a Gmail add-on

I'm building a Gmail add-on with 2 steps:
Authorization with Gmail account.
Authenticate to access my service.
Example: The same as Trello add-on:
When I click the button to login, a login form appears like this:
I want to receive data response after sign-in. I've read ActionResponse documentation, but can not find a solution.
How can I receive the data response?
I believe , you are trying to authorize a custom service.
In order to authorize a custom service like trello, you will have to configure oAuth for it.
Create an oAuth service at gmail add-on to request access to trello.
Once the user completes the oAuth flow, you can use the oAuth service to get the access token. Use this token to access the endpoints whenever required.
Refer example
Edit 1:
Action Response
The usage is as follows:
//action
var onTestBtnClick = CardService.newAction().setFunctionName('onTestBtnClick');
//Button
var testBtn = CardService.newTextButton().setText('test').setOnClickAction(onTestBtnClick);
//action handler
function onTestBtnClick(){
//do some action and finally open google.com
return CardService.newActionResponseBuilder()
.setOpenLink(CardService.newOpenLink()
.setUrl("https://www.google.com"))
.build();
}
You need to setup a separate authentication page for your server(3rd party service). The user has to go through the auth process on your page. Once the user successfully authenticates with your page you need to redirect him to the redirect_uri which is passed to your page from the add-on as an url parameter. Script at the redirect_uri will hit your token url endpoint, which you specify when initiating add-ons auth service. If your token url endpoint returns a valid response, authcallback function in your add-on code is triggered which caches the session and lets the user proceed with using your add-on.
Here's a diagram of the overall flow:
Check out this library Google provides to make the implementation easier.
Also checkout my post which goes into more detail on how to connect your 3rd party services to Gmail add-on
Please see this documentation https://isamatov.com/gmail-add-on-connect-non-google-service/
This will provide you the your ans.
You need to the login page url in
setAuthorizationBaseUrl('https://domain/login.php')
The response which you want to receive is need to set in below URL
setTokenUrl('https://domain/response.php')
function getService() {
return OAuth2.createService('Demo Auth')
.setAuthorizationBaseUrl('https://domain/json.php')
.setTokenUrl('https://domain/token.php')
}

How to get code from UBER's authorise api

I am trying to get the code from json using below url using postman.but could able to get the code in json.
uber login link
Moreover when i hit this url in browser i am redirecting to my localhost url with query parameter where i can get the code.
Step 1. Create an OAuth2Credentials object with your client ID, client secret, scopes, and a redirect callback URI to capture the user’s authorization code.
SessionConfiguration config = new SessionConfiguration.Builder()
.setClientId("YOUR_CLIENT_ID")
.setClientSecret("YOUR_CLIENT_SECRET")
.setScopes(yourScopes)
.setRedirectUri(redirectUri)
.build();
OAuth2Credentials credentials = new OAuth2Credentials.Builder()
.setSessionConfiguration(config)
.build()
Step 2. Navigate the user to the authorization URL from the OAuth2Credentials object.
String authorizationUrl = credentials.getAuthorizationUrl();
Step 3. Once the user approves the request, you get an authorization code. Create a credential object to store the authorization code and the user ID.
Credential credential = credentials.authenticate(authorizationCode, userId);
I am confused with step 2 and step 3.
- what should i have to do with authorizationUrl in step 2 ?.
- How can i get authorizationCode in step 3 using authorizationUrl?.
You should follow the OAuth2.0 process, documented in the developer docs. Basically, you configure your OAuth2.0 settings. Your settings will generate a specific authentication URL (including client_id and scopes requested). This URL needs to be opened in a webview. Your users have to login with their Uber account and either approve or deny access to the scopes. This is the URL you get in step 2.
If the users click on approve in the auth webview, the configured redirect URI will be called through the Uber server. This callback will have a URL parameter for the authorizationCode.

Getting refresh token in Android application from Spring OAuth2 based authentication server

I would like to authenticate android application using OAuth2 in my web service. After some research I know that I should use /oauth/authorize endpoint which gives me implicit authentication. However, in the end after redirection to login page and successful login, server returns access token. After it is expired user has to login again. This is a problem in my scenario and I would like to get also refresh token to be able to use it, to get access token when the old one has expired. Is such scenario possible using spring OAuth2?
In your AuthorizationServerConfiguration you should have a TokenServices bean that is implemented by DefaultTokenServices.
defaultTokenServices.setSupportRefreshToken(true); // enable refresh tokens
Then in your client configuration, be sure to set support for refresh tokens.
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("trusted-app")
.authorizedGrantTypes("password", "refresh_token")
.authorities("ROLE_TRUSTED_CLIENT")
.scopes("read", "write")
.resourceIds(resourceId)
.accessTokenValiditySeconds(accessTokenValiditySeconds)
.refreshTokenValiditySeconds(refreshTokenValiditySeconds)
.secret("secret");
}
When you request make a request to the token endpoint, it should include a refresh token.
/oauth/token?grant_type=password&username="+username+"&password="+password
This should get you a new access token
/oauth/token?grant_type=refresh_token&client_id=trusted-app&refresh_token="+refreshToken

How to connect to the Facebook Graph API from Google Apps Script?

I'm trying to connect to the Facebook Graph API via a Google Apps Script but I'm getting an error
I've tried:
function myFunction (name) {
FB.init({
appId : '{your-app-id}',
status : true,
xfbml : true,
version : 'v2.0'
});
var jsonData = UrlFetchApp.fetch("graph.facebook.com/"; + name);
}
I've also tried:
function myFuntion(name) {
window.fbAsyncInit = function() {
FB.init({
appId : 'your-app-id',
xfbml : true,
version : 'v2.0'
});
};
var jsonData = UrlFetchApp.fetch("graph.facebook.com/"; + name);
}
but neither have worked, I always get a:
"ReferenceError: "FB" is not defined." and a "ReferenceError: "window" is not
defined"
and
"(#4) Application request limit reached","type":"OAuthException","code":4}}
despite putting in my facebook app ID into the variable. I know that "window" is part of an external javascript library so that's why I'm unable to use it in a Google Apps Script, but even after looking at other posts I'm still confused on why I get a "FB" is not defined error.
Any ideas on how to solve this?
There are error codes at the bottom of this page:
Facebook Graph API - Error codes
The "OAuthException" has to do with the Login Status. If you get that error, then you aren't logged in, and to get what you want, you need to be logged in.
You can get an App Access Token using a Server to Server request. There are four types of
Access Tokens:
User - to read, modify or write a specific person's Facebook data on their behalf.
App - modify and read the app settings, and publish Open Graph actions.
Page - read, write or modify the data belonging to a Facebook Page.
Client - the client token is used rarely. Very limited Access to Facebook.
Forms of Access Tokens
User access tokens come in two forms: short-lived tokens and long-lived tokens
short-lived - lifetime of about an hour or two - generated via web login
long-lived - lifetime of about 60 days
You probably don't have an App Access Token. You have an App ID, but that's different than an App Token.
You only get your App Token once. You need to run some code to get it.
Note, that you also must know your App Secret in order to run this code. If you don't know, or have your App Secret, then you need to get that.
See if you can run this code:
//A Facebook App Token never changes unless you go to the Facebook Developers Console,
//and you
//change the App Secret. So, do NOT keep requesting a new App Token. Just get it once,
//then
//hard code it into a backend secret function.
// The App Token can be used to modify your App, but you can just do that 'Manually'
function getOneTimeFB_AppToken() {
Logger.log("getOneTimeFB_AppToken ran");
//keep this info secret
//Generate an App Access Token
var myApp_ID = 'Your App ID';
var myAppSecret = 'Your App Secret';
var optnAppTkn = {"method" : "get"};
var getAppTknURL = "https://graph.facebook.com/oauth/access_token?client_id=" + myApp_ID + "&client_secret=" + myAppSecret + "&grant_type=client_credentials"
var getAppTkn = UrlFetchApp.fetch(getAppTknURL, optnAppTkn);
Logger.log("Object returned from GET: " + getAppTkn)
var myAppTkn = getAppTkn.getContentText();
Logger.log("myAppTkn: " + myAppTkn);
};
Run that code, then in the script editor, choose the VIEW menu, and the LOGS menu item. Read what is in the LOGS. Don't keep running this code over and over again. Just run it once if it's successful.
If that code works, then you just successfully communicated with Facebook.
You need to understand what the Tokens can do, and what your options are. If you are not going to get a token from a user through client side authorization, then you need to understand the App Token.
App Tokens allow you to interact with Facebook on behalf of an app rather than a user. This can be used to read YOUR app insights and modify the parameters of YOUR app.
You never want to use an App Token in client side (browser) code. That would be a major security problem.
However, if a user has granted your application publishing permissions, then you can use the App Token to publish content to Facebook on behalf of that person. So, app access token can be used in place of a user access token to make API calls IF your app has been granted publishing permissions.
But how do you get publishing permissions? Well, there is no way to get the initial short term access token through the server. That just makes sense if you think about it in terms of security. You can't get the initial, short term access token any other way than through a client login. So, if you want to do something that isn't within the bounds of the App Access Token, you can't do it without having the user login through client side.
You can achieve a client side login, without using the JavaScript SDK. So, in the case of an Apps Script Stand Alone HTML web app, you can still use Facebook login without needing to link to the Facebook JavaScript SDK. If you need to do that, let me know.
In that code, FB is an object. The object needs to be assigned "key/value" pairs. Every "key/value" pair is an element (property) in the object. The error is directly related to how objects work. That FB object gets assigned values from a link (inside HTML) to the Facebook API. If you are trying to use an HTML link to the Facebook API from server side (.gs) code, it won't work. There are lots of things that could be going wrong. In order to know exactly what is going wrong, we need to know whether that code is in a gs file, or an HTML file inside a <script> tag.
There are a couple of ways to connect to Facebook:
From HTML (Client Side)
From the server with HTTP Requests
It looks like the code you are using is from an example of how to use the Facebook JavaScript SDK that is meant to run from inside HTML. The problem with that, is that Apps Script sanitizes HTML sent to the browser. So, if you try to link to the Facebook JavaScript SDK through the HTML, you may not get access. I know that, in the past, I have not been able to use a link to the Facebook API in HTML with the NATIVE sandboxed mode. I haven't tried the new IFRAME sandbox mode.

must I click "Allow Acess" every time I connect? Google Drive SDK API

I wrote calss that saves refresh and access token in my db. I can generate access token by refresh token too. everything works well. I working with web application. now I have another question:
1)
For example, I have already saved Refresh token. then if another person comes, I should check if that person have refresh token in my database to generate her access token. but I should have her user ID firstly.
2)
to get user ID I need her credentials
For example:
Oauth2.Builder builder = new Oauth2.Builder(new NetHttpTransport(), new JacksonFactory(), credentials);
Oauth2 userInfoService = builder.build();
Userinfo userInfo= userInfoService.userinfo().get().execute();
3)
and to get credentials I need authorizationCode:
Credential credentials = exchangeCode(authorizationCode);
4)
and to get authorizationCode User Should Click "Allow Acess" in order to retrieve that code? is it right?
for example:
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, GoogleStorage.class.getResourceAsStream(CLIENTSECRETS_LOCATION));
flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jsonFactory, clientSecrets, SCOPES).setAccessType("offline").setApprovalPrompt("force").build();
and get URL where autorization code will be retrieved:
flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
for instance URL:
https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force&client_id=695230079990-bus3d9gp31vvv64qq5n4ma9mk8vtc1ck.apps.googleusercontent.com&redirect_uri=http://localhost/oauth2callback&response_type=code&scope=https://www.googleapis.com/auth/drive.file%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile
must one person click that button everytime she try to connect to Drive API? I see web applications, where one person clicks that button only once. how to get Autorization code without every time clicking "Allow Acess". I need to click that only once.
Users do not have to grant access to the app every time they run it. You store their credentials in a database and reuse them when needed.
Check the Java DrEdit guide for a complete sample app showing how to get a complete set of credentials for every request:
https://developers.google.com/drive/examples/java