我是移動應用程序的新手,並且最近新建了一個項目。我正在開發一個Xamarin.Forms應用程序,並嘗試從Azure Active Directory獲取一個訪問令牌,以便能夠訪問其他服務器上的一些Web API服務。如何使用AAD對xamarin.Forms應用程序進行身份驗證
使用下面的代碼我能夠得到響應控制檯應用程序,但不是從Xamarin.forms。 Q1。我如何在PCL中實現這個功能?
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Xamarin.Auth;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization.Json;
internal class UtilityClass
{
public static async Task<string> GetTokenAsync()
{
var authenticationContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(aadInstance, null);
ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);
try
{
if (Token == null)
{
AuthenticationResult result = await authenticationContext.AcquireTokenAsync(audienceApi, clientCredential);
if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");
Token = result.AccessToken;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return Token;
}
public async static Task<TReturn> CallApiAsync<TReturn>(string URI)
{
TReturn result = default(TReturn);
HttpClient client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
client.BaseAddress = new Uri(audienceApi);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetTokenAsync());
var uri = new Uri(string.Format(URI, string.Empty));
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<TReturn>(content);
}
return result;
}
}
在我的PCL的應用方法,試圖通過這種方式訪問它
public App()
{
var CustomerContactList = UtilityClasses.CallApiAsync<List<CustomerContact>>();
}
Q2。我想在本地服務器上運行我的Web API服務並調試Xamarin.Forms App的調用,那麼如何配置我的Visual Studio 2015和Android模擬器以訪問https://localhost:PortNumber/api/getCustomerContacts?
預先感謝您,您的支持
接聽Q2:你不能使用localhost,指定的主機的IP地址機器。確保你的主機和仿真器在同一個網絡上。要回答Q1,我需要測試我的答案,這是不可能的,沒有憑據,所以對不起 –
我的意思是說:你的設備和你的主機在同一個網絡上。對於仿真器,它顯然是在同一個網絡上,但仍然需要使用IP地址sa主機和仿真器使用不同的IP地址 –