How long does the User Token/Client last with Box Platform API? - box-api

I'm developing a server-side application to upload files to Box. I'm using the Box .NET SDK, using JWT for authentication.
Here's how I set up my Box stuff:
var boxConfig = new BoxConfig(clientId, clientSecret, enterpriseId, jwtPrivateKey, jwtPrivateKeyPassword, jwtPublicKeyId);
var boxJwt = new BoxJWTAuth(boxConfig);
var userToken = boxJwt.UserToken(boxAppUserId);
var userClient = boxJwt.UserClient(userToken, boxAppUserId);
Then I use the UserClient object to upload a file to Box once a day.
My question is: Will that UserClient or UserToken ever expire? I want to know if I should get a new UserToken and instantiate a UserClient every time I need to use it, or if I could initialize all these things just once when my application starts up.

The token will expire after roughly one hour. The client is designed to fetch a new user/admin token as necessary so you shouldn't need to worry about it after the client is initially created. You might even try specifying a blank token when initializing the client and let the re-authentication logic handle things from the beginning:
var userClient = boxJwt.UserClient("", boxAppUserId);

Related

How to authenticate with Blockfrost.io API?

So I'm trying to import Cardano Blockchain data like address balance, amount staked, rewards etc into a Google Sheet. I found this project named Blockfrost.io which is an API for accessing Cardano blockchain info and import it into apps etc.
I think I can use this with Google Sheets. Problem is I don't know how to authenticate. I've searched all around on the documentation and it's not clear to me. It seems it's possible if your're building an app or using the terminal.
But I just want to authenticate in the easiest way possible like in the browser address bar that way it would be simple to get the JSON with the info I need and import the info to Google Sheets.
This is where it mentions the Authentication:
https://docs.blockfrost.io/#section/Authentication
I already have an API key to access. But how do I authenticate?
So if I want to check the blockchain metrics (mainnet1234567890 is a dummy key, I won't use mine here):
https://cardano-mainnet.blockfrost.io/api/v0/metrics/project_id:mainnet1234567890
The JSON will still output this:
status_code 403
error "Forbidden"
message "Missing project token. Please include project_id in your request."
Is there a correct way to authenticate on the browser address bar?
It's not clear which BlockFrost API you are using Go JavaScript etc...
the API key goes in as a header on the request object. I was manually trying to connect to the service and found for a request is what I had to do in C#...
var aWR = System.Net.WebRequest.Create(url);
aWR.Method = "GET";
aWR.Headers.Add("project_id", "mainnetTheRestOfMyKeyIsHidden");
var webResponse = aWR.GetResponse();
var webStream = webResponse.GetResponseStream();
var reader = new StreamReader(webStream);
var data = reader.ReadToEnd();
Later I realized I wanted to use their API cause they implement the rate limiter, something I would rather use than build... I use the following with the BlockFrost API in c#
const string apiKey = "mainnetPutYourKeyHere";
const string network = "mainnet";
// your key is set during the construction of the provider.
ServiceProvider provider = new ServiceCollection().AddBlockfrost(network, apiKey).BuildServiceProvider();
// from there individual services are created
var AddressService = provider.GetRequiredService<IAddressesService>();
// The call to get the data looked like
AddressTransactionsContentResponseCollection TXR = await AddressService.GetTransactionsAsync(sAddress, sHeightFrom, sHeightTo, 100, iAddressPage, ESortOrder.Desc, new System.Threading.CancellationToken());
// etc. your gonna need to set the bounds above in terms of block height
Try using postman and include the "project_id" header with api key as the value like this - it will clear up the concept for you I think:enter image description here

How to display push notifications using SignalR in MVC

I am using SignalR in MVC to display information in a basic chat type device in MVC. This is all working ok but I want to display information from a Json payload that has been deserialized like this:
Dim iss As IssueObjectClass = JsonConvert.DeserializeObject(Of object)(json)
The information does not have to being displayed does not just have to be an object it could be a variable as well, for example I could also display this:
Dim key = iss.issue.key
I have the code for the connection using the chat hub device which is displaying basic information (Message and username). Is this the way that I should try and display my Json using SignalR. I know that SignalR is used for real-time web applications but I am unsure on how it could display information that has been fired from a webhook as a Json payload.
This is how I am displaying the messages in the chat hub, but I want to display information that is coming from a webhook unrelated to anything that has been typed on the application. I want to display information from a HTTP POST from JIRA:
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
$('#discussion').append('<li><strong>' + encodedName + '</strong>: ' + encodedMsg + '</li>');
$('#discussion').text = encodedMsg;
How can I integrate SignalR with Json to display it?
It's a pretty simple thing to do, and a common case with SignalR. In your code where to receive and deserialize your object, you just have to call something like:
var context = GlobalHost.ConnectionManager.GetHubContext<YourHub>();
context.Clients.All.broadcastIssue(iss);
On your client you'll have to define a handler this way before you start the connection:
var yourHubProxy = $.connection.yourHub;
yourHubProxy.client.broadcastIssue = function (iss) {
// ...do your stuff...
};
This is very basic code which would need to be better organized, but it should put you on the right track. My advice is you go through the official SignalR documentation, which is extensive and well done, in particular the guides to the APIs.

How to log in programmatically to a web page

I need some help to post username and password to a web page and then invoke the click event for the log in.
In order to better understand what I'm trying to do, a good example could be the following one:
programmatically send to a bank account's web page username and password (in the relevant inputs) and then, once logged in, retrieve the balance.
This means that in my app I'll have a XAML page with 2 textboxes, 1 button and 1 textblock.
Parse a site is quite easy, so that I'd be able to get the balance but I can't send the data to the server for the log in.
I've already read several examples with WP8 but none of them allows me to understand how to proceed with WP8.1 where, apparently, things are little bit different.
I've tried with this code where I assumed the inputs are called "user" and "password":
private async void LogIn_Click(object sender, RoutedEventArgs e)
{
string url = "http://www.something.com";
WebRequest request = WebRequest.Create(url);
string postData = "user=" + textBoxUser.Text + "&password=" + textBoxPassword.Text;
byte[] send = Encoding.UTF8.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
Stream sout = await request.GetRequestStreamAsync();
sout.Write(send, 0, send.Length);
sout.Dispose();
var myHttpClient = new System.Net.Http.HttpClient();
var response = await myHttpClient.GetAsync(url);
var dataBack = await response.Content.ReadAsStringAsync();
//Debug:
Debug.WriteLine(dataBack);
}
Even though I don't receive any error, the inputs in the response are empty and moreover I don't know how to invoke the click event of the button in the web page to submit the data.
In addition, I don't want to open the web page since everything would be managed by the 4 controls of the app.
Is there anybody who can give some suggestion or address me where I can find something which suits my need?
Thanks
Looks like you're already on the right path: putting together the correct POST request the way a browser would send it after the user submits the form.
You may however need to set Referer parameters and maybe a CSRF token or such in addition to naming the parameters correctly. The best approach would be to submit the form in an actual browser and look at the request that it sends via the built-in developer tools, then reverse-engineer that one from within your app.

Box Api v2 java - How to reuse the access-token within 3600 secs

I am using Box Api v2 (java) for integrating my webapp with Box.com.
I forward the user to the authorize url
https://www.box.com/api/oauth2/authorize?response_type=code&client_id=client-id
..and receive the 'code' at my redirect end-point. Using this code, I am able to get the access_token and refresh_token. I know that access_token is valid only for 1 hr.
But can I re-use the access_token within this 3600 sec period?
eg:a user comes back within 30 minutes and tries to fetch/put files
In this scenario, I will need to create a new BoxClient.
So what is the recommended method of client authentication using the existing access token?
If answerer can paste code snippets using the box java api, it would be quite helpful.
Or is the refreshing to get new access_token and refresh_token, the only method available?
BoxClient client = new BoxClient(MY_CLIENT_ID, MY_CLIENT_SECRET);BoxOAuthManager mgr = client.getOAuthManager();
// This is refresh
BoxOAuthRequestObject requestObject = BoxOAuthRequestObject.refreshOAuthRequestObject(REFRESH_TOKEN, MY_CLIENT_ID, MY_CLIENT_SECRET);
BoxOAuthToken newToken = mgr.refreshOAuth(requestObject);
client.authenticate(newToken);
Yes, you can re-use the access token within the 3600-second period. A common pattern for web applications is to store the access_token and refresh_token (and optionally their expiration datetimes) in a database record associated with the user.
what is the recommended method of client authentication using the existing access token?
You'll use the same authentication method as when you first acquired the access token. You don't have to do anything special to reuse it. If the access_token is expired, as determined by either an expiration timestamp comparison or 401 response, you can use the refresh_token to get a new token pair. By refreshing and persisting the token pair in this manner you can keep the user authenticated indefinitely.
BoxOAuthToken accessToken = new BoxOAuthToken(Map) will work here.
// where Map contains
{
"exprires_in":"3600",
"token_type":"bearer",
"refresh_token":"<refresh_token>",
"access_token":"<access_token>"
}
Map authMap;
BoxOAuthToken accessToken = new BoxOAuthToken(authMap);
client.authenticate(newToken);

Is it possible to set naviagtion uri for BackTile click

I have developed wp8 app,
I am updating my app tile at some scenarios,
here the code i have used for update my tile
ShellTile TileToFind = ShellTile.ActiveTiles.First();
StandardTileData NewTileData = new StandardTileData
{
BackgroundImage = new Uri(#"/ApplicationTile.png", UriKind.RelativeOrAbsolute),
Count = NotificationCount,
BackTitle = offers.data.info[0].offer_title,
BackContent = offers.data.info[0].location_area,
};
TileToFind.Update(NewTileData);
Here my doubt is, is it possible to set navigation uri for the BackTile, like as i give the navigation uri in my toast message here
Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast();
toast.Content = "#" + offers.data.info[0].location_area;
toast.Title = offers.data.info[0].offer_title;
toast.NavigationUri = new Uri("/LocationDealsPage.xaml", UriKind.Relative);
toast.Show();
I need to navigate to different pages while click the back tile and front tile.
Anybody please let me know, is that possible are not, if possible please let me know how.
If not possible is there any other way to do this.
Thank you.
Noorul.
There is no way to set a different URI to navigate to when the user taps a tile when the back is displayed.
If you need to navigate to different parts of the app you could use multiple tiles.
Alternatively, if you're remotely updating the back of the tile when there is new information available and you want to do a different action when launching the app and there is new information (e.g. go to straight to that new item rather than the main page) you could do this check when the app is opened. To avoid having to make a[n extra] network request on app start up, you could use a background agent to regularly pull down the latest data (including a flag to detect if there is a new item) so it's there when the app is launched.