Windows 10 IoT Core remove WiFi profile programatically - c#

I need to remove a saved wifi profilefrom code, so that the SoftAP is enabled again. According to the ms docs, there is no way to remove a profile, only disconnect. Is this not possible?
Ms docs for wifi
https://learn.microsoft.com/en-us/uwp/api/windows.devices.wifi.wifiadapter
Device Portal API
https://learn.microsoft.com/de-ch/windows/mixed-reality/device-portal-api-reference#wifi-management
Here is my working code for disconnecting from a wifi using device portal API
// API creds
string username = "Administrator";
string password = "p#ssw0rd
// API request URIs
string apiUri = "http://192.168.1.15:8080/api/wifi/network";
// WiFi details
string wifiInterface = string.Empty;
string wifiProfile = string.Empty;
// WiFi access
WiFiAccessStatus wifiAccess = await WiFiAdapter.RequestAccessAsync();
if (wifiAccess == WiFiAccessStatus.Allowed)
{
// Get WiFi adapter
IReadOnlyList<WiFiAdapter> wifiAdapterResult = await WiFiAdapter.FindAllAdaptersAsync();
WiFiAdapter wifiAdapter = wifiAdapterResult[0];
// Get conn profile / details
ConnectionProfile profile = await wifiAdapter.NetworkAdapter.GetConnectedProfileAsync();
wifiInterface = profile.NetworkAdapter.NetworkAdapterId.ToString();
wifiProfile = profile.ProfileName;
}
// API creds
PasswordCredential credentials = new PasswordCredential("login", username, password);
// HttpClient filter
HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
filter.CookieUsageBehavior = HttpCookieUsageBehavior.NoCookies;
filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
filter.ServerCredential = credentials;
// HttpClient
HttpClient client = new HttpClient(filter);
apiUri = apiUri + "?interface=" + wifiInterface + "&op=disconnect" + "&createprofile=no";
// Request
HttpRequestMessage request = new HttpRequestMessage();
request.Method = new HttpMethod("POST");
request.RequestUri = new Uri(apiUri);
// Send request
try
{
// Response
HttpResponseMessage response = await client.SendRequestAsync(request);
// Again
if (response.Content.ToString().Contains("Authorization Required"))
{
response = await client.SendRequestAsync(request);
}
}
catch
{
// Dispose
client.Dispose();
filter.Dispose();
}
But for deleting a wifi profile, i get 404 not found back from the API. According to the API docs linked above, the request should be ok. Here is my code for deleting a wifi profile
// API creds
string username = "Administrator";
string password = "p#ssw0rd
// API request URIs
string apiUri = "http://192.168.1.15:8080/api/wifi/network";
// WiFi details
string wifiInterface = string.Empty;
string wifiProfile = string.Empty;
// WiFi access
WiFiAccessStatus wifiAccess = await WiFiAdapter.RequestAccessAsync();
if (wifiAccess == WiFiAccessStatus.Allowed)
{
// Get WiFi adapter
IReadOnlyList<WiFiAdapter> wifiAdapterResult = await WiFiAdapter.FindAllAdaptersAsync();
WiFiAdapter wifiAdapter = wifiAdapterResult[0];
// Get conn profile / details
ConnectionProfile profile = await wifiAdapter.NetworkAdapter.GetConnectedProfileAsync();
wifiInterface = profile.NetworkAdapter.NetworkAdapterId.ToString();
wifiProfile = profile.ProfileName;
}
// API creds
PasswordCredential credentials = new PasswordCredential("login", username, password);
// HttpClient filter
HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
filter.CookieUsageBehavior = HttpCookieUsageBehavior.NoCookies;
filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
filter.ServerCredential = credentials;
// HttpClient
HttpClient client = new HttpClient(filter);
apiUri = apiUri + "?interface=" + wifiInterface + "&profile=" + wifiProfile;
// Request
HttpRequestMessage request = new HttpRequestMessage();
request.Method = new HttpMethod("DELETE")
request.RequestUri = new Uri(apiUri);
// Send request
try
{
// Response
HttpResponseMessage response = await client.SendRequestAsync(request);
// Again
if (response.Content.ToString().Contains("Authorization Required"))
{
response = await client.SendRequestAsync(request);
}
}
catch
{
// Dispose
client.Dispose();
filter.Dispose();
}
Edit//
To close this problem, since build 17763, there is a new method for deleting WiFi profiles directly from code available
bool canDelete = wifiProfile.CanDelete;
if (canDelete)
{
ConnectionProfileDeleteStatus deleteStatus = await wifiProfile.TryDeleteAsync();
}

You may be able to call netsh from your program.
netsh wlan delete <profile name> should get you there.

After trying for hours, finally found a solution! For those who are interested, you have to call the "run command" API, which allows you to run certain windows commands
string deleteCommand = "netsh wlan delete profile name=*";
string cmdApi = string.Format("http://192.168.1.15:8080/api/iot/processmanagement/runcommand?command={0}&runasdefaultaccount={1}", GetBase64String(deleteCommand), GetBase64String("no"));
The really important thing to note here is that you have to encode the command as a base64 string, otherwise it won't work!
private string GetBase64String(string stringToConvert)
{
return Convert.ToBase64String(Encoding.UTF8.GetBytes(stringToConvert));
}
With this code, it is finally possible for me to delete either certain wifi profiles, or in the example case above, every saved profile.

Thanks a lot Andy for finding this. I was doing it with command line before but this does work. I added some supporting code around it to help others where I had some issues such as get, delete or post. If it works then I restart IoT to be back in Onboarding mode. Maybe someone will find this helpful.
Logging into the portal as admin may or may not be required but that is how I do it. The if (interfaceGUID != null) was assigned by a previous Api request and can be removed for testing.
private string password = "yourpassword";
private string localhost = "127.0.0.1";
private async Task DeleteProfile()
{
try
{
using (HttpClient client = new HttpClient())
{
if (interfaceGUID != null)
{
string deleteCommand = "netsh wlan delete profile name=*";
using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, string.Format("http://{0}:8080/api/iot/processmanagement/runcommand?command={1}&runasdefaultaccount={2}", localhost, Convert.ToBase64String(Encoding.UTF8.GetBytes(deleteCommand)), Convert.ToBase64String(Encoding.UTF8.GetBytes("no")))))
{
request.Headers.Authorization = CreateBasicCredentials("Administrator");
using (HttpResponseMessage response = await client.SendAsync(request))
{
if (response.IsSuccessStatusCode == true)
{
ShutdownManager.BeginShutdown(Windows.System.ShutdownKind.Restart, TimeSpan.FromSeconds(1));
}
else
{
Debug.WriteLine("Could not delete the profiles. " + response.ReasonPhrase.ToString());
}
}
}
}
client.Dispose();
}
}
catch (Exception ex)
{
Debug.WriteLine("Could not delete the profiles. " + ex.InnerException.ToString());
}
}
private AuthenticationHeaderValue CreateBasicCredentials(string userName)
{
string toEncode = userName + ":" + password;
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
byte[] toBase64 = encoding.GetBytes(toEncode);
string parameter = Convert.ToBase64String(toBase64);
return new AuthenticationHeaderValue("Basic", parameter);
}

Been working on Windows device portal API recently and came across this post. The reason your code got 404 response is because in the API URI, the &profile= expects a Base64 value instead of a text string that you're using. Once you encode the profile name to Base64, it should work.
I believe this isn't explicitly stated in MS's device portal documentation, as I only discovered this by using web browser debugger to inspect Windows Device Portal web page when deleting a WIFI profile.

To close this problem, since build 17763, there is a new method for deleting WiFi profiles directly from code available
bool canDelete = wifiProfile.CanDelete;
if (canDelete)
{
ConnectionProfileDeleteStatus deleteStatus = await wifiProfile.TryDeleteAsync();
}

Related

Why does download pdf using browser require login while using postman does not?

I tried to test my APIs (Direct Download Pdf API) using postman (Send & Download) and all went well and the file was downloaded successfully, no need to set login information. But when i tried to use mozilla browser, it's tell me login required? why?
Here is my response header using postman:
And here when i try using browser, show idm downloader ask username password:
Here is my code
[Authorize]
[HttpGet]
public IHttpActionResult GetDownloadPdf(string date)
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
ResponseData responseData = new ResponseData();
try
{
_logDataBLL.SaveRequestLogRecord(RequestType.GET, MethodBase.GetCurrentMethod().Name);
MA_MS_Agent objdata = new MA_MS_Agent();
//Update - Checking current user still active
var identity = User.Identity as ClaimsIdentity;
if (LoginBLL.isStillActive(identity) == false)
{
dynamic Reject = new ExpandoObject();
Reject.Message = "Authorization has been denied for this request.";
return Content(HttpStatusCode.Unauthorized, Reject);
}
date = "01" + date.Substring(2);
string filename = "1000007"+ "_" + date + ".pdf";
ByteArrayContent pdfByte;
MA_MS_ApplicationParameter Selected_Parameter = AddReferralBLL.getAppParameterByCode("APPP025");
string param_value = Selected_Parameter.ApplicationParameter_Value;
string pdfFilePath = param_value + filename;
byte[] bytes = null;
if (File.Exists(pdfFilePath))
{
bytes = System.IO.File.ReadAllBytes(pdfFilePath);
}
else
{
return BadRequest();
}
using (var m = new MemoryStream())
{
pdfByte = new ByteArrayContent(bytes);
}
if (pdfByte == null)
{
responseData = _responseDataBLL.GenerateResponseData(HttpStatusCode.NoContent);
responseData.status = true;
return Ok(responseData);
}
response.Content = pdfByte;
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = filename;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("Application/pdf");
//response.Headers.Add("MyHeader", "MyHeaderValue");
//response.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json");
return ResponseMessage(response);
}
catch (Exception ex)
{
string error = ex.Message;
if (ex.InnerException != null)
error += " => " + ex.InnerException.Message;
responseData = _responseDataBLL.GenerateResponseData(HttpStatusCode.InternalServerError, error);
_logDataBLL.SaveResponseLogRecord(JsonConvert.SerializeObject(responseData));
return Content(HttpStatusCode.InternalServerError, responseData);
}
}
Oauth2 Flow:
When you try to access your api from a browser, like your Mozilla browser, you need to get the access token from your oauth server first. So your clientapp should authorize the user and use the users token for the authorisation.
Getting the authtoken depends from your Auth Server.
The keycloak project explains how you can authorize in a JS-ClientApplication like an angular or react app and pass the bearer token to another api.
https://www.keycloak.org/docs/latest/securing_apps/index.html#_javascript_adapter
Without Authorisation:
you are forcing authorization in your code.
You should replace the [Authorize] attribute with [AllowAnonymous]
[AllowAnonymous]
[HttpGet]
public IHttpActionResult GetDownloadPdf(string date)
{
//.. code
}
Update better link:
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/simple?view=aspnetcore-3.1
Looks like your URL requires a basic auth.
It is working in postman because you are sending an Authorization header in postman. But in the browser, when you try to open that URL, it doesn't have any authorization header.

[Azure DataCatalog]: Read the data from Azure data catalog glossary Unauthorized error?

I was try to post the excel data in azure data catalog. i was written in console Application.
my code is
static void Main()
{
string DefaultCatalog = "DefaultCatalog";
string DefaultGlossary = "DefaultGlossary";
string fullUri = string.Format("https://api.azuredatacatalog.com/catalogs/{0}/glossaries/{1}/terms?api-version=2016-03-30",
DefaultCatalog, DefaultGlossary);
HttpWebRequest request = WebRequest.Create(fullUri) as HttpWebRequest;
request.KeepAlive = true;
request.Method = "GET";
request.Accept = "application/json;adc.metadata=full";
request.Headers.Add("Authorization", AccessToken().Result.CreateAuthorizationHeader());
request.AllowAutoRedirect = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response != null && response.StatusCode == HttpStatusCode.Redirect)
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
var itemPayload = reader.ReadToEnd();
JToken terms;
JObject.Parse(itemPayload).TryGetValue("value", out terms);
if (terms != null)
{
var r = JsonConvert.DeserializeObject<JArray>(terms.ToString());
}
}
}
}
static async Task<AuthenticationResult> AccessToken()
{
string clientId = "MyClientId";
string client_secret = "MyClientSecret";
string tenentId = "MytenentId";
if (_authResult == null)
{
// Resource Uri for Data Catalog API
string resourceUri = "https://api.azuredatacatalog.com/";
string redirectUri = "https://login.live.com/oauth20_desktop.srf";
string authorityUri = "https://login.windows.net/MytenentId/oauth2/authorize";
AuthenticationContext authContext = new AuthenticationContext(authorityUri);
_authResult = await authContext.AcquireTokenAsync(resourceUri, clientId, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Always));
//ClientCredential cc = new ClientCredential(clientId, client_secret);
//_authResult = await authContext.AcquireTokenAsync(resourceUri, cc);
}
return _authResult;
}
I want to get the list of glossary from my azure datacatalog. But it always returning Unauthorized error.
"The remote server returned an error: (403) Forbidden."
my error is
You'll need to use to get the correct token:
string authorityUri = "https://login.windows.net/common/oauth2/authorize";
Hope this helps,
Monica
make sure you are in the list of glossary admins.
Also ADC has great code samples in github which does what you want to do, check it out:
https://github.com/Azure-Samples/data-catalog-bulk-import-glossary
The Data Catalog contains only delegate permission.
But, I tried using Application permission. So, It throws Unauthorized after I changed it into user login based (Delegated Permission).
Now it's fixed.
Thanks for sharing the answer #Monica and #Max

SendAsync using HttpClient in Xamarin Forms not awaiting

I am busy developing a Xamarin forms application and have been struggling the last 2 days to get a successful post to my webApi from the application. Posting to the WebApi from the chrome Postman app works perfectly but I cannot seem to get it going from the application.
This is the webApi method that I am trying to call:
[HttpPost]
public string Authenticate(HttpRequestMessage request)
{
string JsonObj = request.Content.ReadAsStringAsync().Result;
AuthToken _authToken = JsonConvert.DeserializeObject<AuthToken>(JsonObj);
int UserID = DomainAuth.ValidateDomainAccount(_authToken.Username, _authToken.Password);
if(UserID > 0)
{
_authToken.UserID = UserID;
_authToken.Authenticated = true;
}
else
{
switch(UserID)
{
case -99:
_authToken.AuthMessage = "The entered domain account does not exist";
break;
case -98:
_authToken.AuthMessage = "The entered domain account does not have application access";
break;
case -97:
_authToken.AuthMessage = "Incorrect username and password combination";
break;
}
}
return JsonConvert.SerializeObject(_authToken);
}
I was originally trying to post to IIS Express but read on a post that this cannot be done when using an external device so the api is hosted in IIS now.
This is the method that my viewmodel command calls:
public async void Login()
{
Tuple<bool, string> AuthCheck = await _authService.AuthenticateDomainAccount(_username, _password);
if (AuthCheck.Item1) //Item1: True / False value indicating if the login was a success
{
Helpers.Settings.Username = _username;
await _navigationService.NavigateAsync("Synchronization");
}
else
{
FeedbackMsg = AuthCheck.Item2; // Item2: Message indicating why the login has failed.
}
}
And lastly this is the method that makes the api call:
public async Task<Tuple<bool, string>> AuthenticateDomainAccount(string _Username, string _Password)
{
AuthToken _authToken = new AuthToken { Username = _Username, Password = _Password };
HttpClientHandler handler = new HttpClientHandler();
using (var client = new HttpClient(handler, false))
{
client.BaseAddress = new Uri(BaseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "User/Authenticate"))
{
req.Content = new StringContent(JsonConvert.SerializeObject(_authToken), Encoding.UTF8, "application/json");
try
{
var response = await client.SendAsync(req);
Debug.WriteLine("################# HERE I AM ################");
var result = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
string a = "a";
}
}
}
return null;
}
When I step through the application it hits the SendAsync line, but instead of waiting for it to return as expected, it skips the lines below it and immediately returns null as per the final line of the method.
Can anyone shed some light on this?
I think the issue over here is with the Uri you are trying to hit. SendAsync method may be throwing a 404 because of incorrect Url.
Please change the following line:
using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "User/Authenticate"))
to
using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "api/User/Authenticate"))
assuming your BaseAddress ends with a '/' at the end, else it will be
using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "/api/User/Authenticate"))

PowerBI and Azure AD Headless Login

I am trying to embed PowerBI dashboards into my customer MVC portal. My customers don't have AAD accounts, so they can't login to Live when they come to the website, they log into my MVC website with individual authority.
I have registered my App on PowerBI/AAD and have the ClientID and Secret. I make the call to AAD and get an Authorization Code which I then use to get an Athentication Token which the is returned successfully.
When ever I use the access token to get a dashboard it is continually rejected with a 403 Forbidden.
I have gone through all the samples from Microsoft, but they require a user login prompt. I have reviewed the ADAL2.0 code which refers to the AcquireToken Method, but this was deprecated in ADAL3 and replaced with AcquireTokenAsync which has different parameters and I am using this in my example below.
Here is the function to get the token:
protected AuthenticationResult GetAccessToken()
{
string pBiUser = Properties.Settings.Default.PowerBIUser;
string pBiPwd = Properties.Settings.Default.PowerBIPwd;
string pBiClientId = Properties.Settings.Default.PowerBIClientId;
string pBiSecret = Properties.Settings.Default.PowerBIClientSecret;
TokenCache TC = new TokenCache();
ClientCredential CC = new ClientCredential(pBiClientId,pBiSecret);
string AU = Properties.Settings.Default.PowerBIAuthority;
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authenticationContext
= new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(AU, TC);
AuthenticationResult result = authenticationContext.AcquireTokenAsync("https://analysis.windows.net/powerbi/api"
,CC).Result;
if (result == null)
{
throw new InvalidOperationException("Failed to obtain the PowerBI token");
}
return result;
}
I then take the result token and call. The response receives the 403:
protected PBIDashboards GetDashboards(AuthenticationResult authResult)
{
PBIDashboards pbiDashboards = new PBIDashboards();
var baseAddress = new Uri("https://api.powerbi.com");
using (var httpClient = new System.Net.Http.HttpClient {BaseAddress = baseAddress})
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("authorization",
"Bearer " + authResult.AccessToken);
using (**var response** = httpClient.GetAsync("v1.0/myorg/dashboards").Result)
{
string responseData = response.Content.ReadAsStringAsync().Result;
//Deserialize JSON string
pbiDashboards = JsonConvert.DeserializeObject<PBIDashboards>(responseData);
if (pbiDashboards != null)
{
var gridViewDashboards = pbiDashboards.value.Select(dashboard => new
{
Id = dashboard.id,
DisplayName = dashboard.displayName,
EmbedUrl = dashboard.embedUrl
});
}
}
}
return pbiDashboards;
}
Based on the error message(403), the issue is relative to the permission.
And AFAIK the is no such permission we can use when we acquire the access token using the client credentials flow for the Power BI REST. You can refer the permission for the figure below:
To get the token for the Power BI REST without user interaction, we can use the Resource owner password credentials flow. And you can use the 3rd party library PowerBI.Api.Client which already implement this.
After a lot of research, you can make a direct AJAX call to get the token:
private async Task<string> GetAccessToken()
{
string pBiUser = Properties.Settings.Default.PowerBIUser;
string pBiPwd = Properties.Settings.Default.PowerBIPwd;
string pBiClientId = Properties.Settings.Default.PowerBIClientId;
string pBiSecret = Properties.Settings.Default.PowerBIClientSecret;
string pBITenant = Properties.Settings.Default.PowerBITenantId;
string tokenEndpointUri = "https://login.microsoftonline.com/"+pBITenant+"/oauth2/token";
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", pBiUser),
new KeyValuePair<string, string>("password", pBiPwd),
new KeyValuePair<string, string>("client_id", pBiClientId),
new KeyValuePair<string, string>("client_secret", pBiSecret),
new KeyValuePair<string, string>("resource", "https://analysis.windows.net/powerbi/api")
});
using (var client = new HttpClient())
{
HttpResponseMessage res = client.PostAsync(tokenEndpointUri, content).Result;
string json = await res.Content.ReadAsStringAsync();
AzureAdTokenResponse tokenRes = JsonConvert.DeserializeObject<AzureAdTokenResponse>(json);
return tokenRes.AccessToken;
}
}
Once you have the string AccessToken, you can then call the Dashboards request.
protected PBIDashboards GetDashboards(string token)
{
PBIDashboards pbiDashboards = new PBIDashboards();
var baseAddress = new Uri("https://api.powerbi.com");
using (var httpClient = new System.Net.Http.HttpClient {BaseAddress = baseAddress})
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("authorization",
"Bearer " + token);
using (var response = httpClient.GetAsync("v1.0/myorg/dashboards").Result)
{
string responseData = response.Content.ReadAsStringAsync().Result;
//Deserialize JSON string
pbiDashboards = JsonConvert.DeserializeObject<PBIDashboards>(responseData);
if (pbiDashboards != null)
{
var gridViewDashboards = pbiDashboards.value.Select(dashboard => new
{
Id = dashboard.id,
DisplayName = dashboard.displayName,
EmbedUrl = dashboard.embedUrl
});
}
}
}
return pbiDashboards;
}
This will provide you the list of dashboards and the dashboard Id to call the PowerBI API to build the embeded page in Javascript. I used hidden input fields to store the access token and embed URL to pass over to the Javascript call.
// check if the embed url was selected
var embedUrl = document.getElementById('embed').value;
if (embedUrl === "")
return;
// get the access token.
accessToken = document.getElementById('token').value;
// Embed configuration used to describe the what and how to embed.
// This object is used when calling powerbi.embed.
// You can find more information at https://github.com/Microsoft/PowerBI-JavaScript/wiki/Embed-Configuration-Details.
var config = {
type: 'dashboard',
accessToken: accessToken,
embedUrl: embedUrl
};
// Grab the reference to the div HTML element that will host the dashboard.
var dashboardContainer = document.getElementById('dashboard');
// Embed the dashboard and display it within the div container.
var dashboard = powerbi.embed(dashboardContainer, config);

WebAuthenticationBroker Issues

I having some issues with the data being returned by the WebAuthenticationBroker in my app. The api I'm connecting to utilizes OAuth 1.0a. I'm able to get the Broker to pull up the authorization page, but ResponseData from the Broker is just url to the page that contains the key value pair for the OAuth Verifier. So I tried a web request to try and get that data, but end up getting 405: Method Not allowed error from the page. Here is my code...
public async Task Authorize(string oAuthAuthorizeUrl)
{
// Start WebAuthenticationBroker
System.Uri StartUri = new Uri(oAuthAuthorizeUrl);
System.Uri EndUri = new Uri(oAuthCallBack);
WebAuthenticationResult auth = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, StartUri, EndUri);
if (auth.ResponseStatus == WebAuthenticationStatus.Success)
{
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync(auth.ResponseData);
HttpContent content = response.Content;
string responseText = await content.ReadAsStringAsync();
string oauth_verifier = null;
string[] keyValPairs = responseText.Split('&');
for (int i = 0; i < keyValPairs.Length; i++)
{
String[] splits = keyValPairs[i].Split('=');
switch (splits[0])
{
case "oauth_verifier":
oauth_verifier = splits[1];
break;
}
}
oAuthVerifier = oauth_verifier;
}
}
is this how the Broker is supposed to work? I assumed it would send back the data with the Verifier. Thanks for the help.

Categories

Resources