问题
I am attempting to use AppCenter authentication flow in my Xamarin Application with Azure B2C to authenticate with a Azure function and retrieve the user id.
in App.xaml.cs
using System;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Rooms.Services;
using Rooms.Views;
using Microsoft.AppCenter;
using Microsoft.AppCenter.Auth;
using System.Threading;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Linq;
namespace Rooms
{
public partial class App : Application
{
private HttpClient _client;
private HttpClient Client
{
get
{
return _client ?? new HttpClient();
}
}
public App()
{
InitializeComponent();
}
protected override void OnStart()
{
// Handle when your app starts
AppCenter.Start("ios={Your Xamarin iOS App Secret}" +
"android={app-secret};",
typeof(Auth));
SignIn();
MainPage = new MainPage();
}
async void SignIn()
{
try
{
// Sign-in succeeded.
UserInformation userInfo = await Auth.SignInAsync();
string token = userInfo.AccessToken;
string uri = "https://{function-name}.azurewebsites.net/.auth/me";
string userId = string.Empty;
Client.DefaultRequestHeaders.Add("x-zumo-auth", token);
var response = await Client.GetAsync(uri);
string rs = await response.Content.ReadAsStringAsync();
var rj = JsonConvert.DeserializeObject<JArray>(rs);
userId = rj.Children().FirstOrDefault().Children<JProperty>().FirstOrDefault(x => x.Name == "user_id").Value.ToString();
}
catch (Exception e)
{
// Do something with sign-in failure.
}
}
}
}
response returns:
{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Date: Mon, 28 Oct 2019 00:58:08 GMT
WWW-Authenticate: Bearer realm="{function-app-name}.azurewebsites.net" authorization_uri="https://{B2C-tenant}.b2clogin.com/{B2C-tenant}.onmicrosoft.com/oauth2/v2.0/authorize?p={B2C-tenant}"
[....]
}}
ADD settings in Azure Function authenticagion settings:
-Client Secret: matches Application secret in App Center.
-Client ID: matches application id from B2C application registration
-Issuer Url: matches endpoint Url in my B2C sign in/sign up user flow
Azure Function Azure Active Directory Settings
The Auth settings in App Center is linked to my B2C tenant and user flow.
App Center Auth Settings
B2C Sign up and sign in User Flow Policy
Update:
There was a problem with my HttpClient property :(
It Should be this:
return _client = _client ?? new HttpClient();
Instead of this:
return _client ?? new HttpClient();
This fixes the 401 not Authorized issue. Now I am receiving an empty string. I should be receiving a JWT token.
来源:https://stackoverflow.com/questions/58584931/using-app-center-auth-and-azure-b2c-to-authenticate-with-azure-functions