簡體   English   中英

如何使用AAD對xamarin.Forms應用程序進行身份驗證

[英]How to Authenticate a xamarin.Forms app using AAD

我是移動應用程序的新手,最近參加了一個新項目。 我正在開發Xamarin.Forms應用程序,並嘗試從Azure Active Directory獲取訪問令牌,以便能夠訪問另一台服務器上的某些Web API服務。

使用下面的代碼,我能夠在控制台應用程序上獲得響應,但不能從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

預先感謝您對我們的支持

您需要配置本地IIS Express來處理它在外部IP上收到的請求,請按照此處的步驟進行操作,如果您遇到注釋,請調試步驟

干杯

Q1。 如何在PCL中實現此功能?

如果您看一下此鏈接,將會發現一些適合您的內容https://forums.xamarin.com/discussion/19021/using-xamarin-auth-with-xamarin-forms

用下面的redirectUrl替換auth和authorizeUrl應該可以工作,盡管我還沒有測試過。

https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code

var auth = new OAuth2Authenticator (
clientId: "clientId",
scope: "",
authorizeUrl: new Uri ("https://login.microsoftonline.com/{yourtenant}/oauth2/authorize?"),
redirectUrl: new Uri ("urn:ietf:wg:oauth:2.0:oob"));

Q2。 我想在本地服務器上運行Web API服務並調試來自Xamarin.Forms App的調用,因此如何配置Visual Studio 2015和Android仿真器以訪問https:// localhost:PortNumber / api / getCustomerContacts

在IIS中,將本地網站公開到特定端口,然后在android模擬器中使用

https://10.0.2.2:portNumber/api/getCustomerContacts

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM