Getting ArcGIS Online OAuth2 access token via c#

1337
1
10-27-2019 10:56 PM
MichaelBell
New Contributor III

I'm trying to get a token for ArcGIS Online using c# (well, more specifically SSIS). I've got a url I can use which works well, and I can hit it and get what I need in Chrome, but it won't work through c# using a WebClient.

I can get other jsons through it through SSIS/C# WebClient, but NOT ArcGIS Online for some reason. The url works through Chrome, but won't yield an answer through SSIS/C# WebClient.

My code (with client id/secret/credentials) is:

string webResource = "https://mymaps.maps.arcgis.com/sharing/rest/oauth2/token?client_id=MYCLIENTID&client_secret=MYCLIENTSECRET&grant_type=client_credentials";WebClient wc = new WebClient();string json = wc.DownloadString(webResource);

I would then parse the json.

Currently I'm getting:

DTS Script Task has encountered an exception in user code: project name: ST_0a306cf2e1634509bea49b75b7d93265 Exception has been thrown by the target of an invocation. at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()

I have created an application, as described in https://developers.arcgis.com/labs/rest/get-an-access-token/

An example of the returned json (through Chrome) is:

{"access_token":"blahblahblahcrazywords..","expires_in":7200}

0 Kudos
1 Reply
nicogis
MVP Frequent Contributor

Try with RestSharp ( https://restsharp.dev/getting-started/ )

 RestRequest r = new RestRequest("https://...../sharing/rest/oauth2/token/");
 r.AddParameter("client_id","ewrwerwerwerwewer");
 r.AddParameter("client_secret","assfwerwerwerwerewrwerwerfgfg");
 r.AddParameter("grant_type","client_credentials");
 r.Method = RestSharp.Method.POST;
 r.RequestFormat = DataFormat.Json;
 RestClient c = new RestClient();
 IRestResponse rs = c.Execute(r);
 JsonDeserializer a = new JsonDeserializer();
 Dictionary<string, string> d = a.Deserialize<Dictionary<string, string>>(rs);
 d["access_token"];‍‍‍‍‍‍‍‍‍‍‍
0 Kudos