Get Access Token - Design Automation for Revit - autodesk-forge

I have created the app, was able to debug the source code.
Also received Client ID and Client secret.
I need your help to understand how to get access token.
Basically this part -
enter image description here
It will be really helpful if you can provide a sample code on how to send the HTTP request as I am novice to web API's.
I have added this code to my solution -
enter image description here
enter image description here
Thanks,
STR

Here is a working example, how to obtain an Access token.
You need to add NewtonSoft.Json nuget package to your project to run it.
public class TokenModel
{
[JsonProperty("access_token")]
public string AccessToken;
}
public async Task<string> GetToken()
{
var credentials = new Dictionary<string, string>();
credentials.Add("client_id", "YOUR_CLIENT_ID");
credentials.Add("client_secret", "YOUR_CLIENT_SECRET");
credentials.Add("grant_type", "YOUR_GRANT_TYPE");
credentials.Add("scope", "YOUR_SCOPE");
var content = new FormUrlEncodedContent(credentials);
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("https://developer.api.autodesk.com");
var response = await client.PostAsync("/authentication/v1/authenticate", content);
if (response.IsSuccessStatusCode)
{
var responseData = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TokenModel>(responseData).AccessToken;
}
}
}
And simple usage:
var token=await GetToken();
It is not perfect, I've tried to simplify all the moments.

Related

How to set up google api in asp.net mvc to access docs

About 6 months ago I set up a web application in the google developers console so that employees of our internal web site could initiate emails which would read a template doc in a google account, merge some fields and then download a pdf version of it to email out.
Now we have to move those template docs to a different google managed domain/user account so I've made copies of the documents in the new account and updated our references with the new doc ids.
In addition, the email I had when I originally created this application in the google dev console is going away as of the first of the year. So I also have to recreate the app under a new account.
I've done that and matched all the settings of the original app. However, when I try to access a document I get the error Google.Apis.Auth.OAuth2.Responses.TokenResponseException: 'Error:"unauthorized_client", Description:"Unauthorized", Uri:""'
I had followed this page in setting up the original user authentication. I know there was a ton of trial and error before I actually got it working and I must be forgetting something. I'm wondering if it's tied to needing to reauthenticate the new app. Although I'm specifying the new clientid and clientsecret from the new app, I don't get the popup asking me to give permission to the app. I would expect with the new credential info that it would open that window asking me to give permission. Here's that file for reference. Any ideas?
public class AuthCallbackController : Google.Apis.Auth.OAuth2.Mvc.Controllers.AuthCallbackController
{
protected override FlowMetadata FlowData => new AppFlowMetadata();
}
public class AppFlowMetadata : FlowMetadata
{
private static readonly IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = AwsSecrets.GoogleCreds.ClientId,
ClientSecret = AwsSecrets.GoogleCreds.ClientSecret
},
Scopes = new[] {DriveService.Scope.Drive},
DataStore = new FileDataStore("Drive.Api.Auth.Store")
});
public override IAuthorizationCodeFlow Flow => flow;
public override string GetUserId(Controller controller)
{
return "userid";
}
}
public class GoogleController : TECWareControllerBase
{
private readonly IGoogleCredentialService _gservice;
public GoogleController(IGoogleCredentialService gservice)
{
_gservice = gservice;
}
public async Task<ActionResult> IndexAsync(CancellationToken cancellationToken)
{
var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);
if (result.Credential != null)
{
_gservice.SaveRefreshToken(result.Credential.Token.RefreshToken);
return View();
}
return new RedirectResult(result.RedirectUri);
}
}
I finally found a way to get this working.
First off in this method
private static readonly IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = AwsSecrets.GoogleCreds.ClientId,
ClientSecret = AwsSecrets.GoogleCreds.ClientSecret
},
Scopes = new[] {DriveService.Scope.Drive},
DataStore = new FileDataStore("Drive.Api.Auth.Store")
});
I had to change the FileDataStore("Drive.Api.Auth.Store") key to something else like FileDataStore("GoogleAuth")
That forced the authentication to fire up.
Unfortunately, google then complained about an invalid redirect uri. The following code returned a redirect uri of http://localhost:11224/AuthCallback/IndexAsync which didn't even exist in my web application's Authorized redirect uris. It should have been http://localhost:11224/MVC/AuthCallback/IndexAsync. So in the url result's redirect url I changed it to what it should have been which allowed me to complete the authorization. Now I can access the documents in the authenticated account.
var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(cancellationToken);

what is the best way to post http request from ssis package

i want to call a http post request through my ssis package. But not sure what should be the best way of calling a rest api post method. Please help .
You can use this method within a Script Task to make the api call using httpclient:
public void Post(Produto produto)
{
var client = new HttpClient;
client.BaseAddress = new Uri("https://localhost:5001/api/");
client.DefaultRequestHeaders.Clear();
//client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Add("ApiKey", "");
var jsonBody = JsonConvert.SerializeObject(produto);
client.PostAsync("createproduto", new StringContent(jsonBody, Encoding.UTF8, "application/json"));
}
You can make use of the namespace System.Net.WebClient to make the Http request with the help of Script Task in SSIS. Following example shows how this can be achieved. The example was created in SSIS 2008 R2.
public void Main()
{
Variables varCollection = null;
Dts.VariableDispenser.LockForRead("User::RemoteUri");
Dts.VariableDispenser.LockForRead("User::LocalFolder");
Dts.VariableDispenser.GetVariables(ref varCollection);
System.Net.WebClient myWebClient = new System.Net.WebClient();
string webResource = varCollection["User::RemoteUri"].Value.ToString();
string fileName = varCollection["User::LocalFolder"].Value.ToString() + webResource.Substring(webResource.LastIndexOf('/') + 1);
byte[] data;
using (WebClient client = new WebClient())
{
data = client.DownloadData(webResource);
}
FileInfo file = new System.IO.FileInfo(fileName);
file.Directory.Create(); // If the directory already exists, this method does nothing.
File.WriteAllBytes(file.FullName, data);
Dts.TaskResult = (int)ScriptResults.Success;
}

Azure Mysql HTTP REST API . Get JSON Web Token

I'm trying to connect to my Azure Mysql via http rest api (https://learn.microsoft.com/en-us/rest/api/mysql/) without success. The problem is that i can't get the JSON Web Token from my Web App. Situation:
Azure Web App ----- rest api ----> Azure MySql
I guess i need to 'register' this Mysql Server resource in active directory but seems i can't do it.
I followed this tutorial (https://blogs.msdn.microsoft.com/jpsanders/2017/03/17/accessing-azure-app-services-using-azure-ad-bearer-token-2) but i have the same problem : i can't register MySql in Azure Active Directory .
So, how can i obtain a JSON Web Token for Mysql HTTP REST API ?
Thanks!
-------- AD PROPIETARY ROLE FOR MYSQL RESOURCE (NOT MYSQL SERVER) --
---------------- CODE ----------------------------------------------
//
// https://blogs.msdn.microsoft.com/jpsanders/2017/03/17/accessing-azure-app-services-using-azure-ad-bearer-token-2/
//
public static class AzureActiveDirectory
{
// the AD Authority used for login. For example: https://login.microsoftonline.com/myadnamehere.onmicrosoft.com
public static string authority = "";
// the Application ID of this app. This is a guid you can get from the Advanced Settings of your Auth setup in the portal
public static string clientId = "";
// the key you generate in Azure Active Directory for this application
public static string clientSecret = "";
// the Application ID of the app you are going to call.This is a guid you can get from the Advanced Settings of your Auth setup for the targetapp in the portal
public static string resource = "";
static public async Task<AuthenticationResult> GetS2SAccessTokenForProdMSAAsync()
{
var task = await GetS2SAccessToken(authority, resource, clientId, clientSecret);
return task;
}
static async Task<AuthenticationResult> GetS2SAccessToken(string authority, string resource, string clientId, string clientSecret)
{
var clientCredential = new ClientCredential(clientId, clientSecret);
AuthenticationContext context = new AuthenticationContext(authority, false);
AuthenticationResult authenticationResult = await context.AcquireTokenAsync(
resource, // the resource (app) we are going to access with the token
clientCredential); // the client credentials
return authenticationResult;
}
}
AzureActiveDirectory.authority = "https://login.microsoftonline.com/********/";
AzureActiveDirectory.clientId = "********";
AzureActiveDirectory.clientSecret = "********";
AzureActiveDirectory.resource = "https://management.azure.com/";
try
{
AuthenticationResult token = await AzureActiveDirectory.GetS2SAccessTokenForProdMSAAsync();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "Bearer " + token.AccessToken);
var resp = await client.GetAsync("https://management.azure.com/subscriptions/*******/resourceGroups/MYSQL/providers/Microsoft.DBforMySQL/servers/shoplister/firewallRules?api-version=2017-12-01");
Console.WriteLine(resp.StatusCode.ToString());
Console.WriteLine();
}
catch (Exception e) { Console.WriteLine(e); }
--------------- AFTER CHANGES NOW GETTING UNAUTHORIZED ------------
I'm compiling the important points from our discussion in the comments that led to a solution:
Use https://management.azure.com as the resource identifier when acquiring the access token
Use https://login.microsoftonline.com/tenant-id-here/ as the authority (you can also use a verified domain name instead of the id). This defines which AAD tenant you authenticate against
The access token must be attached with new AuthenticationHeaderValue("Bearer", token.AccessToken) in C#, so that the resulting header is Authorization: Bearer tokengoeshere
Finally make sure you have granted permissions to the right app. There can be apps with an identical or similar name.

OCR on Windows Phone 8 WP8

I'm new to the world of programming, and am trying to develop an app that uses OCR.
I want the app to convert a singular receipt into text (nothing too complex).
However my problem is that i'm finding a lack of information for OCR on WP8, and how to implement it.
I would have though that it's a built in function of WP and that information would be easily accessible as to how to implement it.
Anyone know where I could look, or a simple example snippet of code I could use?
Not wanting a subscription based service.
Microsoft recently released the OCR Library for Windows Runtime. Jerry Nixon has posted a video guiding you though it, and there is also an msdn article.
Jerry Nixon's Blog
MSDN
You can try using the same OCR service that the Bing Lens uses. If you haven't tried it: open camera, change lens to bing lens and try it out
The service endpoint is http://ocrrest.bingvision.net/V1. It also gives you information about the location of the detected text with their bounding boxes
Probably some fiddler analysis will help you to send your image in a similar fashion.
I have a little snippet below which expects the image as byte array
public static readonly string ocrServiceUrl = "http://ocrrest.bingvision.net/V1"; // was: "platform.bing.com/ocr/V1";
public static readonly string ocrLanguage = "en";
public static async Task<JsonObject> MakeOcrJSON(byte[] image)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/Recognize/{1}", ocrServiceUrl, ocrLanguage));
request.Method = "POST";
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(image, 0, image.Length);
}
try
{
using (HttpWebResponse response = (HttpWebResponse) (await request.GetResponseAsync()))
{
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
var json = JsonObject.Parse(responseStream.ReadToEnd());
return json;
}
}
}
catch (WebException we)
{
using (Stream responseStream = we.Response.GetResponseStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OcrResponse));
OcrResponse ocrResponse = (OcrResponse)serializer.ReadObject(responseStream);
string ErrorMessage = "Unknown Error";
if (ocrResponse.OcrFault.HasValue)
{
ErrorMessage = string.Format(
"HTTP status code: {0} Message: {1}",
ocrResponse.OcrFault.Value.HttpStatusCode,
ocrResponse.OcrFault.Value.Message);
}
throw new Exception(ErrorMessage);
}
}
}

Create empty file using Document List API 3.0

I am developing a feature which need to create a new empty file(not document) to Google drive, now I am using document list API 3.0 and I am referring to the document: https://developers.google.com/google-apps/documents-list/#uploading_a_new_document_or_file_with_both_metadata_and_content.
I will upload a zero byte file to the Google drive to generate the empty file.
Now I have a problem during request step 1 and request step 2. After the first Post[resumable-create-media link] request I successfully got the upload location. Then when I request put method to the location, I got a 404 not found error. All of the requests have "GData-Version: 3.0" and "Authorization: accessToken" headers.
I searched a lot from the forum and figured out how to create empty document but could not figure out how to create empty file. Here is my code, could anybody help to see which part is wrong? Thanks in advance.
private final static String PARAM_CONTENT_TYPE = "Content-Type";
private final static String PARAM_UPLOAD_LENGTH = "X-Upload-Content-Length";
private final static String PARAM_UPLOAD_TYPE = "X-Upload-Content-Type";
private final static String CONTENT_TYPE_XML = "application/atom+xml";
private final static String URI_RESUMABLE_RESOURCE = "https://docs.google.com/feeds/upload/create-session/default/private/full";
private final static String ENTITY_NEW_FILE = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><entry xmlns=\"http://www.w3.org/2005/Atom\" "
+ "xmlns:docs=\"http://schemas.google.com/docs/2007\"><title>{0}</title></entry>";
#Override
public boolean createNewFile() throws IOException {
String uri = null;
if (ROOT.equals(parentResourceId))
uri = URI_RESUMABLE_RESOURCE;
else
uri = URI_RESUMABLE_RESOURCE + "/%3A" + parentResourceId + "/contents";
try {
StringEntity entity = new StringEntity(MessageFormat.format(ENTITY_NEW_FILE, getName()), Constants.ENCODING);
Map<String, String> headers = new HashMap<String, String>();
headers.put(PARAM_CONTENT_TYPE, CONTENT_TYPE_XML);
headers.put(PARAM_UPLOAD_LENGTH, "0");
headers.put(PARAM_UPLOAD_TYPE, "text/plain");
Map<String, String> params = new HashMap<String, String>();
params.put("convert", "false");
HttpResponse response = helper.execMethodAsResponse(uri, new PostMethod(entity), headers, params);
String location = null;
if ((location = response.getFirstHeader("Location").getValue()) != null) {
headers = new HashMap<String, String>();
headers.put(PARAM_CONTENT_TYPE, "text/plain");
headers.put("Content-Range", "bytes 0-0/0");
//FIXME: Problem occurs here, this put invocation will return 404 not found error.
JsonObject obj = helper.execMethodAsJson(location, new PutMethod(new ByteArrayEntity(new byte[0])), headers, null);
if (obj != null) {
decorateFile(this, obj.get("entry").getAsJsonObject());
return true;
}
}
} catch (UnsupportedEncodingException e) {
}
return false;
}
The easiest way to create an empty file on Google Drive is to use the Google Drive API v2 and send a service.files.insert(File content) request.
You can use the Java sample from the Reference Guide and edit it to not include a MediaContent: https://developers.google.com/drive/v2/reference/files/insert
I have figured out the problem, according to this link: Google Documents List API file upload 400 response
The second put request does not need any additional headers such as "GData-Version: 3.0" and "Authorization: Bearer ****", etc. The only thing need to do is new a put request with the location URI, then it will return response with 201 status code.
Thanks all.