Giter Site home page Giter Site logo

azure-samples / active-directory-xamarin-native-v2 Goto Github PK

View Code? Open in Web Editor NEW
161.0 52.0 77.0 2.44 MB

This is a simple Xamarin Forms app showcasing how to use MSAL.NET to authenticate work or school and Microsoft personal accounts with the Microsoft identity platform, and access the Microsoft Graph with the resulting token.

License: MIT License

C# 76.68% PowerShell 23.26% Batchfile 0.06%
aadv2 mobile-app ms-graph xamarin-forms

active-directory-xamarin-native-v2's Introduction

page_type languages products description urlFragment
sample
csharp
powershell
azure-active-directory
You have a Xamarin mobile application and you want it to consume Microsoft Graph or your own Web Api using Microsoft Identity Platform to acquire tokens.
active-directory-xamarin-native-v2

A Xamarin mobile application using Microsoft identity platform (formerly Azure AD v2.0)

Build status

About this sample

Scenario

You have a mobile application and you want it to consume either Microsoft Graph or your own Web API using the Microsoft Identity Platform to acquire tokens.

Structure of the repository

This repository contains a two-part tutorial - a basic scenario and a more advanced with broker scenario. Choose the one that best suits your scenario, or go through both to understand the differences between the implementations.

Sub folder Description
1-Basic This sample app shows how to use the Microsoft identity platform endpoint to sign-in a user interactively and display their profile

Topology
2-With-broker This chapter adds additional support for the broker (Microsoft Authenticator), which enables more complex scenarios, like device related conditional access and SSO.

Topology

How to run this sample For Xamarin Forms (not MAUI)

To run this sample, you'll need:

  • Visual Studio 2019. Install or update Visual Studio with the following workloads:

    • Universal Windows Platform Development
    • Mobile Development with .Net

    Then from the "Individual Components" tab, make sure these additional items are selected:

    • Android SDK setup (API level 27)
    • Windows 10 SDK (10.0.17134.0)
    • Android SDK level 27 (oreo) and 28 (pie), and Android SDK build tools 27.0.3 are also required. These are not installed through the VS Installer, so instead use the Android SDK Manager (Visual Studio > Tools > Android > Android SDK Manager…)
  • An Internet connection

  • A Windows, OS X, or Linux machine (necessary if you want to run the app on their respective platforms)

  • An Azure Active Directory (Azure AD) tenant. For more information on how to get an Azure AD tenant, see How to get an Azure AD tenant

  • A user account in your Azure AD tenant. This sample will not work with a Microsoft account (formerly Windows Live account). Therefore, if you signed in to the Azure portal with a Microsoft account and have never created a user account in your directory before, you need to do that now.

  • Setup Xamarin.iOS for Visual Studio (if you want to run the iOS app) - This will require Visual Studio on PC, and on a Mac Machine where XCode 14.0 is installed.

Step 1: Clone or download this repository

From your shell or command line:

git clone https://github.com/Azure-Samples/active-directory-xamarin-native-v2.git

or download and exact the repository .zip file.

Given that the name of the sample is pretty long, and so are the name of the referenced NuGet packages, you might want to clone it in a folder close to the root of your hard drive, to avoid file size limitations on Windows.

Then navigate to the sub-folder of your choice, 1-Basic or 2-With-broker

Community Help and Support

Use Stack Overflow to get support from the community. Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before. Make sure that your questions or comments are tagged with [msal dotnet].

If you find a bug in the sample, please raise the issue on GitHub Issues.

If you find a bug in msal.Net, please raise the issue on MSAL.NET GitHub Issues.

To provide a recommendation, visit the following User Voice page.

Contributing

If you'd like to contribute to this sample, see CONTRIBUTING.MD.

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

More information

For more information, see MSAL.NET's conceptual documentation:

active-directory-xamarin-native-v2's People

Contributors

acomsmpbot avatar aiwangmicrosoft avatar bgavrilms avatar danieldobalian avatar dependabot[bot] avatar gladjohn avatar henrik-me avatar jennyf19 avatar jmprieur avatar masatoru avatar mathilderoussel avatar neha-bhargava avatar nick-goloborodko avatar pmahend1 avatar pmaytak avatar rwike77 avatar sameerk-msft avatar sasukeh avatar trwalke avatar v-michaelmi avatar vibronet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

active-directory-xamarin-native-v2's Issues

Rename master branch to msal2x, and msal3x branch to master

Why?

The default branch for this sample is msal3x
and the master branch is featuring msal2x
this is confusing for customers (and maintainers)

Impact:

no impact on the quickstart as there is no quickstart yet for this scenario

What?

We want to:

  • rename the current master branch to msal2x
  • rename the current msal3x to master
  • set the default branch of the repository to be master

cc: @jennyf19 @henrik-me @trwalke @bgavrilMS

Cannot authenticate apps created on Azure Free tier

I was able to successfully authenticate an application on the Android platform (SDK 25) in my Premium P1 subscription. However, when I created an application in my free Azure AD portal and switched out the GUIDs, the authentication flow breaks after I enter my username, choose Personal for the realm, and enter my known good password. The error page that is presented in Chrome has login.live.com as the URL and the simple "We're unable to complete your request. Microsoft account is experiencing technical problems. Please try again later."

I tried manually setting the authority in the App.cs file to each of https://login.microsoftonline.com/tenant/, https://login.microsoftonline.com/mailnew.....microsoftonline.com/ (which is my AD tenant name), https://login.microsoftonline.com/consumers/, and https://login.microsoftonline.com/corporate/. None of these worked and all resulted in the same error message. Can you offer guidance on the changes that need to be made, other than the App Id, in order to support Azure Free AD tier?

[Edit: More info] Let me throw this in. I decided to create an additional user in my AD. After saving, I notice that the new user is labeled (in the Source column) as an Azure Active Directory account. My administrative account is listed as a Microsoft Account. This seems odd if they are in the same AD. I will add this: I was one of the first to sign up for a free Azure developer account several years ago. I receive an Office 365 Enterprise E3 Developer MSDN billing statement every month. Could my account be sort of an oddball account? Thanks!

Xamarin.iOS / Xamarin.Android

Does this library support Xamarin.iOS or just Xamarin.Forms?

I am trying to create a new instance of the PublicClientApplication class and I keep getting an exception:

'The type initializer for 'Microsoft.Identity.Client.Internal.PlatformPlugin' threw an exception.'

It looks like it is failing at:

at Microsoft.Identity.Client.Internal.PlatformPlugin.LoadPlatformSpecificAssembly()
at Microsoft.Identity.Client.Internal.PlatformPlugin.InitializeByAssemblyDynamicLinking()
at Microsoft.Identity.Client.Internal.PlatformPlugin..cctor()

never look into tokencache

I'm creation a Xamarin.forms app using B2C AD; I update to version 2.0.0 and change my code to use IAccount and not IUser but now I have a couple of errors (one in iOS) and the other in Android.
On iOS I receive a object not reference not set exception during login while in Android it seems that TokenCache if never used and every time I have to login again

Sample does not build with VS 2019

Failure seems to be related to Xamarin

error XF001: Xamarin.Forms targets have been imported multiple times. Please check your project file and remove the duplicate import(s).

System.InvalidOperationException: On Xamarin.Android, you have to specify the current Activity from which the browser pop-up will be displayed using the WithParentActivityOrWindow method.

On executing this line
authResult = await App.PCA.AcquireTokenInteractive(App.Scopes)
.WithParentActivityOrWindow(App.ParentWindow)
.ExecuteAsync();

It is throwing Exception:

05-22 14:32:40.165 E/mono (29592):
05-22 14:32:40.165 E/mono (29592): Unhandled Exception:
05-22 14:32:40.165 E/mono (29592): System.InvalidOperationException: On Xamarin.Android, you have to specify the current Activity from which the browser pop-up will be displayed using the WithParentActivityOrWindow method.
05-22 14:32:40.165 E/mono (29592): at Microsoft.Identity.Client.AcquireTokenInteractiveParameterBuilder.Validate () [0x00018] in <48941809037546559a7e7308bdd45147>:0
05-22 14:32:40.165 E/mono (29592): at Microsoft.Identity.Client.AbstractAcquireTokenParameterBuilder1[T].ValidateAndCalculateApiId () [0x00000] in <48941809037546559a7e7308bdd45147>:0 05-22 14:32:40.165 E/mono (29592): at Microsoft.Identity.Client.AbstractPublicClientAcquireTokenParameterBuilder1[T].ExecuteAsync (System.Threading.CancellationToken cancellationToken) [0x00000] in <48941809037546559a7e7308bdd45147>:0
05-22 14:32:40.165 E/mono (29592): at Microsoft.Identity.Client.AbstractAcquireTokenParameterBuilder1[T].ExecuteAsync () [0x00006] in <48941809037546559a7e7308bdd45147>:0 05-22 14:32:40.165 E/mono (29592): at Variance.ViewModels.MainPageViewModel+<OnSignInSignOut>d__12.MoveNext () [0x00285] in C:\Mobility\test\Variation\App\Variance\Variance\ViewModels\MainPageViewModel.cs:78 05-22 14:32:40.165 E/mono (29592): --- End of stack trace from previous location where exception was thrown --- 05-22 14:32:40.165 E/mono (29592): at (wrapper dynamic-method) System.Object.24(intptr,intptr) 05-22 14:32:40.165 E/mono (29592): at (wrapper native-to-managed) System.Object.24(intptr,intptr) 05-22 14:32:40.172 E/mono-rt (29592): [ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidOperationException: On Xamarin.Android, you have to specify the current Activity from which the browser pop-up will be displayed using the WithParentActivityOrWindow method. 05-22 14:32:40.172 E/mono-rt (29592): at Microsoft.Identity.Client.AcquireTokenInteractiveParameterBuilder.Validate () [0x00018] in <48941809037546559a7e7308bdd45147>:0 05-22 14:32:40.172 E/mono-rt (29592): at Microsoft.Identity.Client.AbstractAcquireTokenParameterBuilder1[T].ValidateAndCalculateApiId () [0x00000] in <48941809037546559a7e7308bdd45147>:0
05-22 14:32:40.172 E/mono-rt (29592): at Microsoft.Identity.Client.AbstractPublicClientAcquireTokenParameterBuilder1[T].ExecuteAsync (System.Threading.CancellationToken cancellationToken) [0x00000] in <48941809037546559a7e7308bdd45147>:0 05-22 14:32:40.172 E/mono-rt (29592): at Microsoft.Identity.Client.AbstractAcquireTokenParameterBuilder1[T].ExecuteAsync () [0x00006] in <48941809037546559a7e7308bdd45147>:0
05-22 14:32:40.172 E/mono-rt (29592): at Variance.ViewModels.MainPageViewModel+d__12.MoveNext () [0x00285] in C:\Mobility\test\Variation\App\Variance\Variance\ViewModels\MainPageViewModel.cs:78
05-22 14:32:40.172 E/mono-rt (29592): --- End of stack trace from previous location where exception was thrown ---
05-22 14:32:40.172 E/mono-rt (29592): at (wrapper dynamic-method) System.Object.24(intptr,intptr)
05-22 14:32:40.172 E/mono-rt (29592): at (wrapper native-to-managed) System.Object.24(intptr,intptr)

AppReg Portal cant enter msal redirect uri

https://github.com/Azure-Samples/active-directory-xamarin-native-v2/tree/master/1-Basic

When following optional steps to create your own app reg in your own tenant step 6 says the following

  1. In the list of pages for the app, select Authentication..
    In the Redirect URIs | Suggested Redirect URIs for public clients (mobile, desktop) section, check the option of the form msal://auth

The portal validation prevents you from saving your changes as it doesn't like the format of the msal.

image

the hacky work around is to edit the manifest and hand enter the msal string

image

Crashes when offline

When I run this offline this is what happens:
image

Your v1 of this project had a problem in that it would not work offline unless a web api was defined. I was hoping this would have fixed that.

Thanks

Surfrat.

code sample throws an error for Xamarin.iOS project

When I try to run the code sample project locally, I get the below-mentioned error.
Severity Description Project File Line Suppression State
Error Can't resolve the reference 'System.String System.String::TrimStart(System.Char)', referenced from the method 'Microsoft.Identity.Json.Schema.JsonSchema Microsoft.Identity.Json.Schema.JsonSchemaBuilder::ResolveReferences(Microsoft.Identity.Json.Schema.JsonSchema)' in 'mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'. UserDetailsClient.iOS

I am using Visual Studio Professional 2017 version 15.8.6

Login Issue

The only the changes made to the sample app that ApplicationId is used mine but when run it and clicked Signin Microsoft dialog open for authentication input username and password clicked signin it redirect back to app with nothing no error nothing happen and tried to debug it but after below line executes breakpoint never hit.
AuthenticationResult ar = await App.PCA.AcquireTokenAsync(App.Scopes, App.UiParent);

Linker issues in v4 both platform

Android:
error MSB4018: The "LinkAssemblies" task failed unexpectedly.
Mono.Linker.MarkException: Error processing method: 'System.Void Microsoft.Azure.Services.AppAuthentication.AdalAuthenticationContext/d__0::MoveNext()' in assembly:
'Microsoft.Azure.Services.AppAuthentication.dll' ---> Mono.Cecil.ResolutionException: Failed to resolve
System.Threading.Tasks.Task`1<Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult> Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions::AcquireTokenAsync(Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext,System.String,System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential)

iOS:
error MT2101: Can't resolve the reference
'System.Threading.Tasks.Task`1<Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationResult> Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions::AcquireTokenAsync(Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext,System.String,System.String,Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential)',
referenced from the method 'System.Void Microsoft.Azure.Services.AppAuthentication.AdalAuthenticationContext/d__0::MoveNext()'
in 'Microsoft.IdentityModel.Clients.ActiveDirectory.Platform, Version=3.14.2.11, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

Microsoft.Identity.Client.MsalClientException: User canceled authentication in Android and iOS.

This sample is working fine for me in both Android and iOS and thank you for this great sample. But I'm facing only one exception with steps below

  1. Tap on sign-in button, it will redirect to browser to ask login.
  2. But if I want to close browser without login will result the exception "Microsoft.Identity.Client.MsalClientException: User canceled authentication".
    Please help me to handle this exception.

Sample displays error for single-tenancy application.

I've created and configured an app registration in our portal. For the Authentication section I've only enabled the first suggested Redirect URL (msalXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX://auth) and have configured the Supported Account Types as Accounts in this organizational directory only (XX XXXXXX only - Single tenant) - this is deliberate as the app is for our organisation's use only, we do not want to permit other organisations' users to access it.

Selecting the SIGN IN button takes us to our organisations sign-in page and the two-factor works correctly. However I then get an error dialog displayed which says AADSTS50194: Application 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' is not configured as a multi-tenant application. Usage of the /common endpoint is not supported for such applications created after '10/15/2018'. Use a tenant-specific endpoint or configure the application to be multi-tenant.

I am currently unable to make progress on this. All posts I have found to date seem to recommend multi-tenancy and/or not using the /common endpoint - I'm not able to do the first and I'm already not doing the second.

Can anyone please suggest a way forward on this please.

NullReferenceException in iOS only

I am getting a runtime error:
System.NullReferenceException: Object reference not set to an instance of an object
When i click on Sign in button.
the error is occurring at this step (PCA is null):

PCA = new PublicClientApplication(ClientID)
                {
                    RedirectUri = $"msal{App.ClientID}://auth",
                };  

Complete Error:

System.NullReferenceException: Object reference not set to an instance of an object at Microsoft.Identity.Core.TokenCacheAccessor.GetTeamId () [0x0003f] in <772466974f16475694ca93a5f7a70108>:0 at Microsoft.Identity.Core.TokenCacheAccessor..ctor () [0x0001c] in <772466974f16475694ca93a5f7a70108>:0 at Microsoft.Identity.Core.Telemetry.TelemetryTokenCacheAccessor..ctor () [0x00000] in <772466974f16475694ca93a5f7a70108>:0 at Microsoft.Identity.Client.TokenCache..ctor () [0x00000] in <772466974f16475694ca93a5f7a70108>:0 at Microsoft.Identity.Client.PublicClientApplication..ctor (System.String clientId, System.String authority) [0x00014] in <772466974f16475694ca93a5f7a70108>:0 at Microsoft.Identity.Client.PublicClientApplication..ctor (System.String clientId) [0x00000] in <772466974f16475694ca93a5f7a70108>:0 at UserDetailsClient.App..ctor () [0x00009] in Downloads/active-directory-xamarin-native-v2-master/UserDetailsClient/UserDetailsClient/App.cs:30

Only iOS is giving me this . Android Version is working fine.
I am using Visual Studio for Mac

Cannot get Android to complete login process

I have integrated the code from this sample into my Xamarin.Forms app. I have configured Azure according to my best understanding of the documentation, and have made a painstaking emulation of the sample code, including the BrowserTabActivity XML block in the AndroidManifest.

The end result is that it works perfectly on UWP. I am able to login and make other Microsoft graph calls, so I know the Azure configuration is correct, at least for UWP.

However, I cannot get it to work with Android. It goes through the login process all the way to the last step in authentication, which is the dialog that says, "Are you trying to log in to {my app name}?" The process stalls there. The dialog will neither continue, nor cancel. If I tap the continue button rapidly, then I get an error that too many authentication attempts have been made, so I know that it is communicating with Azure.

If I change the sample app ClientID to mine, it also works on UWP, but on Android I get the same problem that I am seeing in my app. It seems that would suggest an Azure configuration problem. But why does it work on UWP? How can one even have different configurations per platform for a "Desktop + Devices" app registration? Are there some extra Android-specific settings that need to be made somewhere?

Is there any way you could share the Azure app configuration manifest for this sample (redacted of course) so I could compare it to mine?

Any help would be greatly appreciated.

Microsoft.Identity.Client 1.1.4.0: UIParent missing constructor UIParent(Activity activity)

I've installed Microsoft.Identity.Client, Version=1.1.4.0 and have downloaded the sample application. I am trying to make the Xamarin solution that is as similar as possible to the sample application.

They both have the same version of Microsoft.Identity.Client but when expanding the region above the UIParent Class, the sample application uses monoandroid81 while our app uses netstandard1.3.

How can I use the UIParent with the signature: public UIParent(Activity activity)?
I'm guessing to make my solution have a similar structure, I have to change the project from using netstandard1.3 to monoandroid81. How would I go about doing this?

Access Violation

Visual Studio 2017.

-- Running the sample without modification: UserDetailsClient.UWP with Windows Mobile Emulator 10.0.14393.0 WVGA 4 inch 512MB causes the app to immediately crash with a Access Denied Native exception at the line:

"PCA = new PublicClientApplication(ClientID);"

Switching to the Mobile Emulator 10.0.15063.0 WVGA 4 inch 512MB the sample works as expected.

-- Running the UserDetailsClient.iOS without modification, the user token is never cached. The line:

AuthenticationResult ar = await App.PCA.AcquireTokenSilentAsync(App.Scopes, App.PCA.Users.FirstOrDefault());

Always results in ar==null. You must always log in to Microsoftr everytime you run the sample -> unlike the working "10.0.15063.0" UWP app.

Hope this helps!

AuthenticationServices.ASWebAuthenticationSession error in Xamarin.iOS

Hi. On a couple of projects (which I ultimately worked back to this one), I get the following error on a MAC using VS Community. Tried on various simulators. All compiles well, just won't deploy. Works fine on Android. Any ideas?

Using

dotnet 2.2.100-preview2-009404

Visual Studio Community 2017 for Mac (Preview)
Version 7.8 Preview (7.8 build 408)

Result

{System.TypeLoadException: Could not set up parent class, due to: Could not load type of field 'Microsoft.Identity.Core.UI.WebviewBase:asWebAuthenticationSession' (5) due to: Could not resolve type with token 0100004c from typeref (expected class 'AuthenticationServices.ASWebAuthenticationSession' in assembly 'Xamarin.iOS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065') assembly:Xamarin.iOS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065 type:AuthenticationServices.ASWebAuthenticationSession member:(null) assembly:/Users/perezs/Library/Developer/CoreSimulator/Devices/DA8EE98B-5174-4B49-8DDC-5E9AE0D27883/data/Containers/Bundle/Application/C76F2597-E876-4655-924F-EBACDBFB64D3/UserDetailsClientiOS.app/Microsoft.Identity.Client.dll type:WebviewBase member:(null)
  at Microsoft.Identity.Client.PublicClientApplication.CreateWebAuthenticationDialog (Microsoft.Identity.Client.UIParent parent, Microsoft.Identity.Client.UIBehavior behavior, Microsoft.Identity.Core.RequestContext requestContext) [0x00015] in <3d9ffb4972634b74a3bbe55d03a0c0a6>:0 
  at Microsoft.Identity.Client.PublicClientApplication+<AcquireTokenForLoginHintCommonAsync>d__22.MoveNext () [0x00088] in <3d9ffb4972634b74a3bbe55d03a0c0a6>:0 
--- End of stack trace from previous location where exception was thrown ---
  at Microsoft.Identity.Client.PublicClientApplication+<AcquireTokenAsync>d__14.MoveNext () [0x0009b] in <3d9ffb4972634b74a3bbe55d03a0c0a6>:0 
--- End of stack trace from previous location where exception was thrown ---
  at UserDetailsClient.MainPage+<OnSignInSignOut>d__1.MoveNext () [0x002a2] in /Users/perezs/dev/code/active-directory-xamarin-native-v2/UserDetailsClient/UserDetailsClient/MainPage.xaml.cs:38 }

Onedrive Connection failure

I'm trying to connect to OneDrive using MSAL token but it's returning error="invalid_token", error_description="Auth error"

This is my code:

    public static string[] Scopes = { "User.Read", "Files.Read", "Sites.Read.All" };
    AuthenticationResult ar = await App.ClientApplication.AcquireTokenSilentAsync(App.Scopes);
    WelcomeText.Text = $"Welcome {ar.User.Name}"; //Login OK here

        //get data from API
        HttpClient client = new HttpClient();
        HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, "https://api.onedrive.com/v1.0/drives");
        message.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", ar.Token);
        HttpResponseMessage response = await client.SendAsync(message);
        string responseString = await response.Content.ReadAsStringAsync();

Anyone know what I'm doing wrong ?

refresh token

Is there anyway for the security token to be persisted (refresh token?) so that when the app closes and re-opens again, the user doesn't have to keep re-entering their credentials?

Master-Detail Xamarin Application starts empty MainPage in iOS and Android

I used your guide to add MSAL to my Xamarin forms app. I followed your guide first and got your sample app working and it worked great in all projects (iOS, Droid and UWP). But when I converted my application which happens to be a Master-Detail Xamarin application, I thought all was fine when I tested UWP first and it worked great. But when I tried iOS and Droid the application started but all I got was a blank MainPage. I think this has something to do with the MainPageRenderer in the iOS and Droid projects. Although I am not sure what needs to be fixed to make a MasterDetail Xamarin application work correctly. I have a sample that I built using the VS 2019 default Xamarin Forms MasterDetail project and added what it needed for MSAL from your project. It fails to display MainPage just like my application. I cleaned out my test project of all obj and Debug folders so it would upload for your inspection. I have spent several days trying to make this work without success. Can you assist me with this issue?

Steve
TestMasterDetail.zip

Android platform specific changes not working.

Android specific changes are not able to implement in the mainactivity.cs as the Microsoft.Identity.Client doesnt have the classes. Look like its working fine, Sample targeting different monversion where as mine is 60. Is the library specific to a target ? In my VS 2017 Preview version its automatically targeting to the below monoversions.

<?xml version="1.0" encoding="utf-8"?> <packages> <package id="Microsoft.CSharp" version="4.3.0" targetFramework="monoandroid60" /> <package id="Microsoft.Identity.Client" version="1.1.0-preview" targetFramework="monoandroid60" /> <package id="Microsoft.NETCore.Platforms" version="1.1.0" targetFramework="monoandroid60" /> <package id="Microsoft.Win32.Primitives" version="4.3.0" targetFramework="monoandroid60" /> <package id="NETStandard.Library" version="1.6.1" targetFramework="monoandroid60" /> <package id="Newtonsoft.Json" version="10.0.3" targetFramework="monoandroid60" /> <package id="System.AppContext" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Collections" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Collections.Concurrent" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.ComponentModel.TypeConverter" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Console" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Diagnostics.Tracing" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Globalization" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Globalization.Calendars" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.IO" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.IO.Compression" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.IO.Compression.ZipFile" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.IO.FileSystem" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.IO.FileSystem.Primitives" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Linq" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Linq.Expressions" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Net.Http" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Net.Primitives" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Net.Sockets" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.ObjectModel" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Reflection" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Reflection.Extensions" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Reflection.Primitives" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Resources.ResourceManager" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Runtime" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Runtime.Extensions" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Runtime.Handles" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Runtime.Numerics" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Runtime.Serialization.Formatters" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Runtime.Serialization.Json" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Runtime.Serialization.Primitives" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Security.Cryptography.Algorithms" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Security.Cryptography.Encoding" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Security.Cryptography.Primitives" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Security.Cryptography.X509Certificates" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Text.Encoding" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Text.Encoding.Extensions" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Text.RegularExpressions" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Threading" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Threading.Tasks" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Threading.Timer" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Xml.ReaderWriter" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Xml.XDocument" version="4.3.0" targetFramework="monoandroid60" /> <package id="System.Xml.XmlDocument" version="4.3.0" targetFramework="monoandroid60" /> <package id="Xamarin.Android.Support.Animated.Vector.Drawable" version="23.3.0" targetFramework="monoandroid60" /> <package id="Xamarin.Android.Support.Design" version="23.3.0" targetFramework="monoandroid60" /> <package id="Xamarin.Android.Support.v4" version="23.3.0" targetFramework="monoandroid60" /> <package id="Xamarin.Android.Support.v7.AppCompat" version="23.3.0" targetFramework="monoandroid60" /> <package id="Xamarin.Android.Support.v7.CardView" version="23.3.0" targetFramework="monoandroid60" /> <package id="Xamarin.Android.Support.v7.MediaRouter" version="23.3.0" targetFramework="monoandroid60" /> <package id="Xamarin.Android.Support.v7.RecyclerView" version="23.3.0" targetFramework="monoandroid60" /> <package id="Xamarin.Android.Support.Vector.Drawable" version="23.3.0" targetFramework="monoandroid60" /> <package id="Xamarin.Forms" version="2.3.4.247" targetFramework="monoandroid60" /> </packages>

Broken on Android 4.4

I can log-in on Android 4.4 but when it tries to return to the app it just displays the app with a blank screen. It seems to work without a problem on Android 8.1.

Can't Sign in - Please use the / Organizations or tenant - specific endpoint.

Hi , I am getting an error ..
"Sorry but we're having trouble with signing you in
AADSTS90130: Application "APLICATION ID" (MY APP ) is not supported over the / common or / consumers endpoints. Please use the / Organizations or tenant - specific endpoint."

How/where can I add the Organizations or tenant - specific endpoint.?

Thanks for your help

AcquireTokenSilentAsync Is not working as expected after updating MSAL 2.0.0-preview

I tried to update the below line of code based on the new documentation.

var authResult = await _authenticationClient.AcquireTokenSilentAsync(
                   Settings.Scopes,
                   _authenticationClient.GetUser(AuthenticatedUser.Id),
                   Settings.B2CAuthority(Settings.DefaultB2CTenant, Settings.DefaultB2CPolicy),
                   true);

This is all about calling AcquireTokenSilentAsync() but I am getting the response of GetAccountsAsync() always null.

IEnumerable<IAccount> accounts = await _authenticationClient.GetAccountsAsync();
IAccount firstAccount = accounts.FirstOrDefault();
var authResult = await _authenticationClient.AcquireTokenSilentAsync(
                    Settings.Scopes,
                    accounts,
                    Settings.B2CAuthority(Settings.DefaultB2CTenant, Settings.DefaultB2CPolicy),
                    true);

Clear browser cookies after logout

Logout() removes all authenticated account from active directory , but the account is still signed in in the browser
`
IEnumerable accounts = await App.PCA.GetAccountsAsync();

while (accounts.Any())
{
await App.PCA.RemoveAsync(accounts.FirstOrDefault());
accounts = await App.PCA.GetAccountsAsync();
}
`
image

so I need to logout the user from the browser too

AcquireTokenInteractive Fails with Broker on iOS 13

Hello,

I've downloaded the sample project and tried the sign in with broker method from an iOS emulator. The emulator is running iOS 13.2. When I click the Sign in With Broker button, an error occurs at the line 112 in MainPage.xaml.cs:

authResult = await App.PCA.AcquireTokenInteractive(App.Scopes) .WithParentActivityOrWindow(App.ParentWindow) .WithUseEmbeddedWebView(true) .ExecuteAsync();

The exception message is:

-canOpenURL: failed for URL: "msauthv2://" - error: "The operation couldn’t be completed. (OSStatus error -10814.)"

Any idea why this may be happening? This issue does not occur on Android.

Where to add redirect_uri?

This works for me configured for your app but when I follow the optional steps to use with my app I get an exception after signing in that there is no redirect_uri. This of course makes perfect sense but I can't find the place in the code to put this redirect uri parameter. Can you help? I'm using it on a UWP app

Xamarin/UWP - AAD B2C compatible library

As per the article below, MSAL should not be used for production.
Is there any other alternative for AAD B2C that can be used for production?

https://azure.microsoft.com/en-us/resources/samples/active-directory-b2c-xamarin-native/

Local account

Can you please add local account access like v1 of this project?

Thanks

Surfrat.

Microsoft.Identity.Client.MsalClientException: Chrome is not installed on the device, cannot proceed with authentication

I use Marshmallow (6.0.0) API Levele 23 with VS2017 emulator for Android. No Chrome has been installed.
When I run it, I got exception.

03-03 16:47:32.108 E/mono    ( 2338): Unhandled Exception:
03-03 16:47:32.108 E/mono    ( 2338): Microsoft.Identity.Client.MsalClientException: Chrome is not installed on the device, cannot proceed with authentication
03-03 16:47:32.108 E/mono    ( 2338):   at (wrapper dynamic-method) System.Object:a768d874-5b11-4a24-afea-0e24259bf690 (intptr,intptr)
03-03 16:47:32.108 E/mono    ( 2338): 	ErrorCode: chrome_not_installed
03-03 16:47:32.109 E/mono-rt ( 2338): [ERROR] FATAL UNHANDLED EXCEPTION: Microsoft.Identity.Client.MsalClientException: Chrome is not installed on the device, cannot proceed with authentication
03-03 16:47:32.109 E/mono-rt ( 2338):   at (wrapper dynamic-method) System.Object:a768d874-5b11-4a24-afea-0e24259bf690 (intptr,intptr)
03-03 16:47:32.109 E/mono-rt ( 2338): 	ErrorCode: chrome_not_installed

This is the same exception that I run it in my another sample xamarin app.
Refer to Custom tabs without Chrome problem

MSAL .NET on iOS 13 does not support system browser

After upgrading to iOS 13/Xcode 11, AcquireTokenInteractive in this sample is no longer working. An exception is raised on line 38 of MainPage.xaml.cs.

"MSAL.Xamarin.iOS.4.3.1.0.MsalClientException: \n\tErrorCode: authentication_canceled\nMicrosoft.Identity.Client.MsalClientException: User canceled authentication.\n at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.VerifyAuthorizationResult () [0x000c1] in :0 \n at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.ExecuteAsync (System.Threading.CancellationToken cancellationToken) [0x0018a] in :0 \n at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync (System.Threading.CancellationToken cancellationToken) [0x001d2] in :0 \n at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.ExecuteAsync (Microsoft.Identity.Client.ApiConfig.Parameters.AcquireTokenCommonParameters commonParameters, Microsoft.Identity.Client.ApiConfig.Parameters.AcquireTokenInteractiveParameters interactiveParameters, System.Threading.CancellationToken cancellationToken) [0x000f2
] in :0 \n at UserDetailsClient.MainPage.OnSignInSignOut (System.Object sender, System.EventArgs e) [0x0024f] in C:\Users\zgreen\Downloads\active-directory-xamarin-native-v2-msal3x\UserDetailsClient\UserDetailsClient\MainPage.xaml.cs:38 "

Transform the repository into a multi-step tutorial

Why?

Now that Xamarin.iOS supports the broker (authenticator), and with the support of broker to Xamarin.Android coming, we want to transform this sample into a multi-step tutorial featuring:

  • without broker
  • with Authenticator (for iOS for the moment)
  • with the mobile app calling its own web API (later)

What?

cc: @jennyf19

Login page shown as not private

I was able to run this sample, make some tweaks to it, and incorporate the code into our iOS app. However another developer runs into a problem when tapping Login and accessing the login page (as shown in the screenshots). This happens both in our app and this app (no code modified after cloning). We are both running the same environment: Visual Studio 2019 on Windows 10, connecting to MacBook Airs (latest OS X version). I even reset her iOS simulator to make sure nothing else was interfering.

Screen 1

Screen 2

AcquireTokenAsync never returns

I'm writing and app that needs to write a file on OneDrive. I have this working on UWP, but on Android, it presents the authentication and I enter username/pw and it displays the "Let this app access your info" page." I press Yes, and nothing happens. The debugger never returns from AcquireTokenAsync, unless I hit the back button. Neither YES/NO do anything. Also I can't be sure the OnActivityResult is being touched, as a breakpoint there doesn't hit. However, BPs in the OnCreate don't get hit either, so I'm not sure if there's a problem setting BPs in MainActivty.cs and debug on device.

I attempted the same steps with this example, and see the exact same behavior. My code is derived from this example.

Could it be a problem with my device (I only have one, galaxy s8). Anything I could try?

Skip Microsoft login page and Taking you to your organization's sign-in page

In Xamarin forms, we require to authenticate our employees only into the app.
So, we need to redirect the user directly to our organization's sign-in page.

I am not sure where to assign this value. Could it be in the Redirect URI?
RedirectUri = $"msal{App.ClientID}://auth",

Would this work if we create an app id and pass it here?

Error when authenticating to /tfs/{tenant}/{siginpolicy} on iOS

There seems to be an issue with the MSAL library as it will allow the user to authenticate on his iOS device with the common endpoint, however, when using the endpoint from the GitHub example ( .../tfs/{tenant}/{signinpolicy} he gets a generic error on the iOS device during the AcquireTokenAsync method. The error on the iOS device is simply "Value cannot be null. Parameter name: str" Any ideas?

Is this actually working?

Registered the proper ClientID and replaced every occurence thereof with the proper Id.

UWP opened a webview which let me enter my email address. This then is usually redirected to a page where I have to enter the password. Instead, here it simply closes the view, no errors given, nothing.

On Android the whole app simply halts and VS debugger tells me that the app was suspended. Nothing else happens.

iOS was not testable due to the lack of a Mac

Xamarin.Forms.Android OnActivityResult is never called

Good day,

We recently upgraded our XF project to MSAL to ver1.1.2. We have no issues with getting the iOS client working. We were unable to get passed the MSAL login page on the Android client. I noticed that the OnActivityResult method is never firing prior to the login screen appearing. I can only trigger the method call when I back out from the login screen. I know the MSAL configuration works because the iOS client can login successfully. I did update the Android manifest to match the example. I did update the file to use our Application ID. Is it important to set the the UIParent context after the LoadApplication(new App()) ? We have it set prior to this line because we want to have the login screen appear right on app startup.

API scopes break the application

Because all of these application samples (UserDetailsClient, TodoListClient/Service, others) all use slightly configurations of the PublicClientApplication, I am finding it difficult to piece together a complete, real-world example of a Xamarin cross-platform application that authenticates to both its own AD Application Registration AND to an exposed API configured as a service with its own scope(s).

I started with the UserDetailsClient application tutorial and was able to authenticate successfully when requesting the single User.Read scope. I also followed the tutorial for the TodoListClient/Service successfully and could fetch and save new TodoList object. My UserDetailsClient is using the configuration of the TodoListClient, with the addition of the MSAL.... redirect URL in order to authenticate the UserDetailsClient.

Unfortunately, as soon as I add my "api://....guid/access_as_user" scope in the authentication setup for the UserDetailsClient application, the application stops working. The Droid project (which is the only one I am testing so far) makes its call to AuthenticationContinuationHelper.SetAuthenticationContinuationEventArgs with the arguments 0, 2003, data>="has extras"

So, whatever the helper is supposed to do in order to allow the activity to continue must be failing due to whatever the PCA is or is not returning.

I would love to see the extra steps needed in order to get this to work. Without the ability to make web service calls I am stuck on building a real application.

One thing I have not implemented yet from the TodoListClient project is the AzureAdServiceCollectionExtensions class in order to get a JwtBearer token. I assume I will need to do something like that in order to make REST calls to the API but at this point I am not there yet. If this is an unnecessary step for Xamarin apps (or if there's something else that needs to be done in order to make REST calls from Droid/iOS) that would be valuable information.

If a complete MSAL Xamarin/Droid/iOS/UWP tutorial including REST calls with Bearer tokens exists, I'd love to see it. I've been fighting to do this most basic real-world proof of concept for a new customer for over a week. Am I just missing some larger architectural strategy that everyone else is doing or is this all just so new that it hasn't seen the real world yet?

Token cache is not persisted on iOS Simulator

Currently, the user that logged in does not get stored in any way. So this part in OnAppearing never gets executed successfully, because there are no users:
var ar = await App.PCA.AcquireTokenSilentAsync(App.Scopes, App.PCA.Users.FirstOrDefault());

Is there any way to persist the logged in user? So that the user does not have to relog every time the application closes and opens.

building project UserDetailsClient.iOS throws iOS sdk version error

Whenever I try to run the project, I get below-mentioned error.

Severity Description Project File Line Suppression State
Error Your application is using the 'AuthenticationServices' framework, which isn't included in the iOS SDK you're using to build your app (this framework was introduced in iOS 12.0, while you're building with the iOS 11.4 SDK.) Please select a newer SDK in your app's iOS Build options. UserDetailsClient.iOS

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.