Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A Helper utility for the samples #185

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
using Microsoft.Identity.Client;
using Android.Content;
using Microsoft.Identity.Client.Platforms.Android;

using Microsoft.Identity.Client.Helper;

namespace UserDetailsClient.Droid
{
[Activity(Label = "UserDetailsClient", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
Expand All @@ -21,7 +22,8 @@ protected override void OnCreate(Bundle bundle)

global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
App.ParentWindow = this;
App.ParentWindow = this;
PCAHelper.Instance.ParentWindow = this;
}

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
Expand Down
3 changes: 2 additions & 1 deletion 1-Basic/UserDetailsClient/UserDetailsClient.UWP/App.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using Microsoft.Identity.Client.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using Microsoft.Identity.Client.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -32,7 +33,8 @@ public MainPage()
string redirectUriWithWAM = $"ms-appx-web://microsoft.aad.brokerplugin/{sid}";

// Then use the following:
LoadApplication(new UserDetailsClient.App(redirectURIForSsoWithoutBroker.AbsoluteUri));
LoadApplication(new UserDetailsClient.App(redirectURIForSsoWithoutBroker.AbsoluteUri));
PCAHelper.Instance.IsUWP = true;
}
}
}
12 changes: 5 additions & 7 deletions 1-Basic/UserDetailsClient/UserDetailsClient/App.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Helper;
using System;
using Xamarin.Forms;

namespace UserDetailsClient
{
public class App : Application
{
public static IPublicClientApplication PCA = null;

/// <summary>
/// The ClientID is the Application ID found in the portal (https://go.microsoft.com/fwlink/?linkid=2083908).
/// You can use the below id however if you create an app of your own you should replace the value here.
Expand All @@ -19,12 +18,11 @@ public class App : Application

public static object ParentWindow { get; set; }

public static IPCAHelper PCA { get; private set; }

public App(string specialRedirectUri = null)
{
PCA = PublicClientApplicationBuilder.Create(ClientID)
.WithRedirectUri(specialRedirectUri?? $"msal{ClientID}://auth")
.WithIosKeychainSecurityGroup("com.microsoft.adalcache")
.Build();
{
PCA = PCAHelper.Init<PCAHelper>(ClientID, Scopes);

MainPage = new NavigationPage(new UserDetailsClient.MainPage());
}
Expand Down
64 changes: 13 additions & 51 deletions 1-Basic/UserDetailsClient/UserDetailsClient/MainPage.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Helper;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
Expand All @@ -19,83 +20,44 @@ public MainPage()

async void OnSignInSignOut(object sender, EventArgs e)
{
AuthenticationResult authResult = null;
IEnumerable<IAccount> accounts = await App.PCA.GetAccountsAsync().ConfigureAwait(false);
try
{
if (btnSignInSignOut.Text == "Sign in")
{
try
var authResult = await PCAHelper.Instance.EnsureAuthenticatedAsync(customizeInteractive: (builder) =>
{
IAccount firstAccount = accounts.FirstOrDefault();
authResult = await App.PCA.AcquireTokenSilent(App.Scopes, firstAccount)
.ExecuteAsync()
.ConfigureAwait(false);
}
catch (MsalUiRequiredException)
{
try
{
var builder = App.PCA.AcquireTokenInteractive(App.Scopes)
.WithParentActivityOrWindow(App.ParentWindow);

if (Device.RuntimePlatform != "UWP")
{
// on Android and iOS, prefer to use the system browser, which does not exist on UWP
SystemWebViewOptions systemWebViewOptions = new SystemWebViewOptions()
{
iOSHidePrivacyPrompt = true,
};

builder.WithSystemWebViewOptions(systemWebViewOptions);
builder.WithUseEmbeddedWebView(false);
}

authResult = await builder.ExecuteAsync().ConfigureAwait(false);
}
catch (Exception ex2)
{
Device.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("Acquire token interactive failed. See exception message for details: ", ex2.Message, "Dismiss");
});
}
}
builder.WithAuthority(AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount);
}).ConfigureAwait(false);

if (authResult != null)
{
var content = await GetHttpContentWithTokenAsync(authResult.AccessToken);
var content = await GetHttpContentWithTokenAsync().ConfigureAwait(false);
UpdateUserContent(content);
}
}
else
{
while (accounts.Any())
{
await App.PCA.RemoveAsync(accounts.FirstOrDefault()).ConfigureAwait(false);
accounts = await App.PCA.GetAccountsAsync().ConfigureAwait(false);
}
await PCAHelper.Instance.SignOutAsync().ConfigureAwait(false);


Device.BeginInvokeOnMainThread(() =>
Device.BeginInvokeOnMainThread(() =>
{
slUser.IsVisible = false;
btnSignInSignOut.Text = "Sign in";
btnSignInSignOut.Text = "Sign in";
});
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("Authentication failed. See exception message for details: ", ex.Message, "Dismiss");
await DisplayAlert("Authentication failed. See exception message for details: ", ex.Message, "Dismiss").ConfigureAwait(false);
});
}
}

private void UpdateUserContent(string content)
{
if(!string.IsNullOrEmpty(content))
if (!string.IsNullOrEmpty(content))
{
JObject user = JObject.Parse(content);

Expand All @@ -114,19 +76,19 @@ private void UpdateUserContent(string content)
}
}

public async Task<string> GetHttpContentWithTokenAsync(string token)
public async Task<string> GetHttpContentWithTokenAsync()
{
try
{
//get data from API
HttpClient client = new HttpClient();
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
PCAHelper.Instance.AddAuthenticationBearerToken(message);
HttpResponseMessage response = await client.SendAsync(message).ConfigureAwait(false);
string responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return responseString;
}
catch(Exception ex)
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(async () =>
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,12 @@
</ItemGroup>


<ItemGroup>
<Compile Include="..\..\..\Helper\PCAHelper.cs">
<Link>Helper\PCAHelper.cs</Link>
</Compile>
<Compile Include="..\..\..\Helper\IPCAHelper.cs">
<Link>Helper\IPCAHelper.cs</Link>
</Compile>
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
using Microsoft.Identity.Client;
using Android.Content;
using Microsoft.Identity.Client.Platforms.Android;

using Microsoft.Identity.Client.Helper;

namespace UserDetailsClient.Droid
{
[Activity(Label = "UserDetailsClient", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
Expand All @@ -20,8 +21,8 @@ protected override void OnCreate(Bundle bundle)
base.OnCreate(bundle);

global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
App.ParentWindow = this;
LoadApplication(new App());
PCAHelper.Instance.ParentWindow = this;
}

protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using Microsoft.Identity.Client.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -30,6 +31,7 @@ public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
PCAHelper.IsUWP = true;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using UIKit;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Platforms.iOS;
using Microsoft.Identity.Client.Helper;

namespace UserDetailsClient.iOS
{
Expand All @@ -26,7 +27,7 @@ public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
App.ParentWindow = new UIViewController(); // iOS broker requires a view controller
PCAHelper.Instance.ParentWindow = new UIViewController(); // iOS broker requires a view controller
return base.FinishedLaunching(app, options);
}

Expand Down
8 changes: 0 additions & 8 deletions 2-With-broker/UserDetailsClient/UserDetailsClient/App.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ namespace UserDetailsClient
{
public class App : Application
{
public static IPublicClientApplication PCA = null;

/// <summary>
/// The ClientID is the Application ID found in the portal (https://go.microsoft.com/fwlink/?linkid=2083908).
/// You can use the below id however if you create an app of your own you should replace the value here.
Expand All @@ -25,14 +23,8 @@ public class App : Application
public static string[] Scopes = { "User.Read" };
public static string Username = string.Empty;

public static object ParentWindow { get; set; }

public App()
{
PCA = PublicClientApplicationBuilder.Create(ClientID)
.WithRedirectUri($"msal{ClientID}://auth")
.Build();

MainPage = new NavigationPage(new UserDetailsClient.MainPage());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
<StackLayout Background="Beige" BackgroundColor="White">
<Label Text="MSAL Xamarin Forms Sample" VerticalOptions="Start" HorizontalTextAlignment="Center" HorizontalOptions="FillAndExpand" />
<BoxView Color="Transparent" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />
<StackLayout x:Name="slUser" IsVisible="False" Padding="5,10">
<StackLayout x:Name="slUser" IsVisible="false" Padding="5,10">
<StackLayout Orientation="Horizontal">
<Label Text="DisplayName " FontAttributes="Bold" />
<Label x:Name="lblDisplayName" />
Expand All @@ -35,8 +35,7 @@
</StackLayout>
</StackLayout>
<BoxView Color="Transparent" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />
<Button x:Name="btnSignInSignOut" Text="Sign in" Clicked="OnSignInSignOut" VerticalOptions="End" HorizontalOptions="FillAndExpand"/>
<Button x:Name="btnSignInSignOutWithBroker" Text="Sign in with broker" Clicked="btnSignInSignOutWithBroker_Clicked" VerticalOptions="End" HorizontalOptions="FillAndExpand"/>
<Button x:Name="btnSignInSignOut" Text="Sign in with broker" Clicked="btnSignInSignOutWithBroker_Clicked" VerticalOptions="End" HorizontalOptions="FillAndExpand"/>
</StackLayout>
</ContentPage.Content>

Expand Down
Loading