Code Monkey home page Code Monkey logo

active-directory-b2c-dotnet-desktop's Introduction

page_type languages products description urlFragment
sample
csharp
azure
This simple sample demonstrates how to use the Microsoft Authentication Library (MSAL) for .NET to get an access token and call an API secured by Azure AD B2C.
active-directory-b2c-dotnet-desktop

WPF application signing in users with Azure Active Directory B2C and calling an API

This branch is using MSAL.NET 4.x. If you are interested in a previous version of the sample using MSAL.NET 2.x, go to the master branch

This simple sample demonstrates how to use the Microsoft Authentication Library (MSAL) for .NET to get an access token and call an API secured by Azure AD B2C.

How To Run This Sample

There are two ways to run this sample:

  1. Using the demo environment - The sample is already configured to use a demo environment and can be run simply by downloading this repository and running the app on your machine. See steps below for Running with demo environment.
  2. Using your own Azure AD B2C tenant - If you would like to use your own Azure AD B2C configuration, follow the steps listed below for Using your own Azure AD B2C tenant. Please note, the api call will only work with domains using {tenantName}.b2clogin.com, as the node.js api used for the api call has been updated to handle b2clogin.com and not login.microsoftonline.com. If using login.microsoftonline.com or a custom b2c domain, you will need to host your own web api (see step 3 below), otherwise, you will see "authorized" when making the api call with this sample as-is.

Using the demo environment

This sample demonstrates how to sign in or sign up for an account at "Wingtip Toys" (the demo environment for this sample) using a WPF Desktop application.

Once signed-in, clicking on the Call API button shows the display name you used when you created your account. The Edit Profile button allows you to change your display name and city. The Logout button logs you out of the application.

Step 1: Clone or download this repository

From your shell or command line:

git clone https://github.com/Azure-Samples/active-directory-b2c-dotnet-desktop.git

Step 2: Run the project

Open the active-directory-b2c-wpf.sln and run the project.

The sample demonstrates the following functionality:

  1. Click the sign-in button at the top of the application screen. The sample works exactly in the same way regardless of the account type you choose, apart from some visual differences in the authentication and consent experience. Upon successful sign in, the application screen will list some basic profile info for the authenticated user and show buttons that allow you to edit your profile, call an API and sign out.
  2. Close the application and reopen it. You will see that the app retains access to the API and retrieves the user info right away, without the need to sign in again.
  3. Sign out by clicking the Sign out button and confirm that you lose access to the API until the exit interactive sign in.

Using your own Azure AD B2C Tenant

In the previous section, you learned how to run the sample application using the demo environment. In this section, you'll learn how to configure this WPF application and a related Node.js Web API with Azure AD B2C sample to work with your own Azure AD B2C Tenant.

Step 1: Get your own Azure AD B2C tenant

First, you'll need an Azure AD B2C tenant. If you don't have an existing Azure AD B2C tenant that you can use for testing purposes, you can create your own by following these instruction.

Step 2: Create your own policies

This sample uses three types of policies: a unified sign-up/sign-in policy, a profile editing policy, and a password reset policy. Create one policy of each type by following the built-in policy instructions. You may choose to include as many or as few identity providers as you wish.

If you already have existing policies in your Azure AD B2C tenant, feel free to re-use those policies in this sample.

Step 3: Register your own Web API with Azure AD B2C

As you saw in the demo environment, this sample calls a Web API at https://fabrikamb2chello.azurewebsites.net. This demo Web API uses the same code found in the sample Node.js Web API with Azure AD B2C, in case you need to reference it for debugging purposes.

You must replace the demo environment Web API with your own Web API. If you do not have your own Web API, you can clone the Node.js Web API with Azure AD B2C sample and register it with your tenant.

How to setup and register the Node.js Web API sample

First, clone the Node.js Web API sample repository into its own directory, for example:

cd ..
git clone https://github.com/Azure-Samples/active-directory-b2c-javascript-nodejs-webapi.git

Second, follow the instructions at register a Web API with Azure AD B2C to register the Node.js Web API sample with your tenant. Registering your Web API allows you to define the scopes that your single page application will request access tokens for.

Provide the following values for the Node.js Web API registration:

  • Provide a descriptive Name for the Node.js Web API, for example, My Test Node.js Web API. You will identify this application by its Name whenever working in the Azure portal.
  • Mark Yes for the Web App/Web API setting for your application.
  • Set the Reply URL to http://localhost:5000. This is the port number that the Node.js Web API sample is configured to run on.
  • Set the AppID URI to demoapi. This AppID URI is a unique identifier representing this Node.jS Web API. The AppID URI is used to construct the scopes that are configured in you single page application's code. For example, in this Node.js Web API sample, the scope will have the value https://<your-tenant-name>.onmicrosoft.com/demoapi/demo.read
  • Create the application.
  • Once the application is created, open your My Test Node.js Web API application and then open the Published Scopes window (in the left nav menu) and add the scope demo.read followed by a description demoing a read scenario. Click Save.

Third, in the index.html file of the Node.js Web API sample, update the following variables to refer to your Web API registration.

var tenantID = "<your-tenant-name>.onmicrosoft.com";
var clientID = "<Application ID for your Node.js Web API - found on Properties page in Azure portal>";
var policyName = "<Name of your sign in / sign up policy, e.g. B2C_1_SiUpIn>";

Lastly, to run your Node.js Web API, run the following command from your shell or command line

npm install && npm update
node index.js

Your Node.js Web API sample is now running on Port 5000.

Step 4: Register your Native app

Now you need to register your native app in your B2C tenant, so that it has its own Application ID.

Your native application registration should include the following information:

  • Provide a descriptive Name for the single page application, for example, My Test WPF App. You will identify this application by its Name within the Azure portal.
  • Mark Yes for the Native Client setting for your application.
  • Create your application.
  • Once the application is created, open your My Test WPF App and open the API Access window (in the left nav menu). Click Add and select the name of the Node.js Web API you registered previously, for example My Test Node.js Web API. Select the scope(s) you defined previously, for example, demo.read and hit Save.

Step 5: Configure your Visual Studio project with your Azure AD B2C app registrations

  1. Open the solution in Visual Studio.
  2. Open the App.xaml.cs file.
  3. Find the assignment for public static string Tenant and replace the value with your tenant name.
  4. Find the assignment for public static string ClientID and replace the value with the Application ID from your Native app registration, for example My Test WPF App.
  5. Find the assignment for each of the policies, for example public static string PolicySignUpSignIn, and replace the names of the policies you created in Step 2, e.g. b2c_1_SiUpIn
  6. Find the assignment for the scopes public static string[] ApiScopes and replace with the scope you created in Step 3, for example, https://<your-tenant-name>.onmicrosoft.com/demoapi/demo.read.
  7. Change the ApiEndpoint variable to point to your Node.js Web API hello endpoint running locally at "http://localhost:5000/hello"

Step 6: Run the sample

  1. Rebuild the solution and run the app.
  2. Click the sign-in button at the top of the application screen. The sample works exactly in the same way regardless of the account type you choose, apart from some visual differences in the authentication and consent experience. Upon successful sign in, the application screen will list some basic profile info for the authenticated user and show buttons that allow you to edit your profile, call an API and sign out.
  3. Close the application and reopen it. You will see that the app retains access to the API and retrieves the user info right away, without the need to sign in again.
  4. Sign out by clicking the Sign out button and confirm that you lose access to the API until the exit interactive sign in.

More information

For more information on Azure B2C, see the Azure AD B2C documentation homepage.

active-directory-b2c-dotnet-desktop's People

Contributors

bgavrilms avatar danieldobalian avatar dependabot[bot] avatar divinci avatar gladjohn avatar gladwinjohnson avatar gsacavdm avatar jennyf19 avatar jmprieur avatar kengaderdus avatar markzuber avatar microsoftopensource avatar msftgits avatar neha-bhargava avatar parakhj avatar peterdrier avatar pmaytak avatar sameerk-msft avatar saraford avatar trwalke avatar v-hearya 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

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

active-directory-b2c-dotnet-desktop's Issues

Adjustments required for WPF on .Net Core 3.1

The sample doesn't work for WPF apps targeting .Net Core 3.1, but with some tweaking I managed to authenticate with B2C to call my APIs.

.WithParentActivityOrWindow() doesn't exist and simply removing it will cause AcquireTokenInteractive() to do nothing when the button is clicked. So I changed redirectUri to http://localhost.

authResult = await app.AcquireTokenInteractive(App.ApiScopes)
                    //.WithParentActivityOrWindow(new WindowInteropHelper(this).Handle) // .Net Framework only?
                    .ExecuteAsync();

Doing the above will allow the WPF app to open the default internet browser to authenticate.

Is the above the only way for .Net Core 3.1 WPF right now? Or is there an equivalent embedded browser method like .WithParentActivityOrWindow()?

Returned user identifier does not match the sent user identifier

Hi parakhj,
I am being in trouble for testing the sample code from you . Eager to get your help

I download your sample code , and just replace the below:
` private static string Tenant = "xxxxx.onmicrosoft.com";
private static string ClientId = "xxxxxx-37e9-4e7d-8a05-xxxx";
public static string PolicySignUpSignIn = "B2C_1_SiUpIn";
public static string PolicyEditProfile = "B2C_1_SiPe";
public static string PolicyResetPassword = "B2C_1_SSPR";

    public static string[] ApiScopes = { "https://xxxxx.onmicrosoft.com/demoapi/demo.read" };
    public static string ApiEndpoint = "http://localhost:5000/hello";`

all of the parameters resource have been created in my aad b2c . when i startup the WPF , there comes the error:
Error Acquiring Token: Microsoft.Identity.Client.MsalServiceException: Returned user identifier does not match the sent user identifier
I feel that my( Sign In or Sign Up policy ) comes wrong but have no idea for the next correcting action.

can you make some suggestions . thanks

Best Regards
wenbo

Following the authentication, AccessToken is null

I have tried the sample code with our two types of users:

  1. A user saved in Azure B2c
  2. A user with a social account from Google

In both cases, I have an AuthenticationResult that looks like this
AccessToken = null
ExpiresOn = 0
IdToken = eyJ0eXAiOiJKV1QiLCJhbGciOi......
Scopes={}
TenantId=null
UniqueId=Valid User Id in AzureB2c
User=

The issue is that I am not getting any AccessToken, Hence I can not call my webApi
I have even created a new Application in Azure B2C, and I still get the same exception.

The Experimental library of Microsoft works on our Azure B2C, so I wonder if this is not related to the implementation itself ?

Any help would be appreciated.

Error Acquring token for Azure AD B2C on native app (WPF) executable file

Hi,

I have been using this sample but when I create an executable file and install it on another machine the errors begin. When I install in on my own PC everthing is fine...

Here is the error message:

Error Acquiring Token: System.InvalidOperationException: Sequence contains no elements at System.Linq.Enumerable.Max[TSource](IEnumerable1 source) at Microsoft.Identity.Client.TokenCache.CalculateSuggestedCacheExpiry() at Microsoft.Identity.Client.TokenCache.d__59.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.Cache.CacheSessionManager.d__10.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.Internal.Requests.RequestBase.d__16.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.d__8.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.Internal.Requests.RequestBase.d__12.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at active_directory_b2c_wpf.MainWindow.<SignInButton_Click>d__1.MoveNext() in C:\Users***\Desktop\active-directory-b2c-dotnet-desktop-msalv3\active-directory-b2c-wpf\MainWindow.xaml.cs:line 36

So what am I doing wrong? And can anybody get the sample app working after they have created an executable file from it?

javascript error

image
I tried to use it with my own tenet. it works when i click sign in but if i clicked sign up , it shows me that error
image

fresh clone fails build because of mix of packages.config and packagereference

msalv3 branch, fresh clone this morning, open solution, build. Fails because of missing nuget packages. Determined it is because there is a packagereference in the csproj. (off-topic: there is a version mismatch between the one in packages.config and the package reference). Delete the PackageReference in csproj, build, and now it fetches all the nuget packages to ..\packages. But it fails to build because one of the nuget packages requires PackageReference (the one I deleted). So I put it back, and now build succeeds because i previously downloaded the nuget packages.

MsalClientException not thrown when login page is closed

I am using the following code:

try
{
    authResult = await app.AcquireTokenInteractive(App.ApiScopes)
                        .WithUseEmbeddedWebView(false)
                        .WithParentActivityOrWindow(new WindowInteropHelper(this).Handle)
                        .ExecuteAsync();
}
catch (MsalClientException ex)
{
    msg = $"Error Acquiring Token: {ex}";
}

I want to handle the case where the user is prompted to the login page, but then closes it or navigates away. For this I have observed two conflicting behaviours being documented.

On the one hand it is stated on the following wiki that MSAL will throw a MsalClientException with the error code authentication_canceled , if when calling AcquireTokenInteractive(), the user closes the process or hits the back button on their browser.
https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/exceptions#common-exceptions

On the other hand on azure documentation it is stated that MSAL.NET cannot detect if the user closes the login page or navigates away.
https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-net-web-browsers#system-browser-experience-on-net

I have confirmed that my code exhibits the later behaviour, so no exception is thrown. If that is the case and MSAL.NET cannot detect such browser behaviour, then is there a valid scenario, where the login page is closed and the program throws a MsalClientException?

Error Acquiring Token - Access to token cache denied

Hi there! This is a great sample that was straight forward to connect to my own B2C tenant and get working quickly.

As I start to experiment with it however, I am running into some issues. I would like to be able to package and distribute an application protected against B2C as a .msix. Having done so, I am running into an issue where an installed copy of the sample is not permitted access to the token cache.

System.UnauthorizedAccessException: Access to the path 'C:\Program Files\WindowsApps\wpfInstallerTest_1.0.3.0_x64__3ae7ag8q269pa\active-directory-b2c-wpf\active_directory_b2c_wpf.exe.msalcache.bin' is denied.```

Is there something that I need to do to make sure that the app can get access to the token cache of my distributed users? It is currently preventing a successful sign in.

Error Acquiring Token: Microsoft.Identity.Client.MsalServiceException: AADB2C90079: Clients must send a client_secret when redeeming a confidential grant.

When Attempting to Sign-In I receive the following Error.

Error Acquiring Token:
Microsoft.Identity.Client.MsalServiceException: AADB2C90079: Clients must send a client_secret when redeeming a confidential grant.
Correlation ID: 12179f8b-25b5-4e26-a8be-2357a203af36
Timestamp: 2019-04-04 23:21:40Z

   at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateErrorResponse(HttpResponse response, RequestContext requestContext)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext, Boolean addCorrelationId)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.<ExecuteRequestAsync>d__10'1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.OAuth2.OAuth2Client.<GetTokenAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.<SendHttpMessageAsync>d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.<SendTokenRequestAsync>d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.<ExecuteAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.<RunAsync>d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.PublicClientApplication.<AcquireTokenForUserCommonAsync>d__23.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Identity.Client.PublicClientApplication.<AcquireTokenAsync>d__11.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter'1.GetResult()
   at active_directory_b2c_wpf.MainWindow.<SignInButton_Click>d__1.MoveNext() in C:\Users\r\source\repos\active-directory-b2c-dotnet-desktop-master\active-directory-b2c-wpf\MainWindow.xaml.cs:line 34
	ErrorCode: invalid_request
	StatusCode: 400
	Claims: 

Please Help. Has some sort of token expired which I need to refresh?

AccessToken is null in authResult

At this point in time, after changing the demo to use my own B2C coordinates, I'm getting logins with the interactive flow, but the bearer token is null.

APIScopes looks like this (tenant urls are incorrect here (I'm hiding my tenant name) but they work in the demo, all the way through the interactive authentications):

        public static string[] ApiScopes = { $"https://{Tenant}.onmicrosoft.com/api/user_impersonation" };
        public static string ApiEndpoint = "https://graph.microsoft.com/";
        public static string AuthorityBase = $"https://{Tenant}.b2clogin.com/tfp/{Tenant}/";

What I'm really trying to do is use graph.microsoft.com/v1.0/Me, which I thought would be simple, given the very, very strong urging by Microsoft to switch to Graph for B2C. Alas, no bearer token, no Graph. (If I can get it working I'll likely push the branch so that there's a decent simple interactive desktop demo for B2C Graph)

I'm not entirely sure I've got this understood correctly, but without a bearer token I can't even get a good error message.

image

`AquireTokenSilent` getting bearer token for the wrong account

If you have authenticated to a wpf app with multiple accounts (during different sessions), it is possible to make a token refresh request that returns a bearer token for the wrong account.

I assume that this is due to the accounts.FirstOrDefault() argument in the token refresh below.

        public async Task PostScreeningRecord(string url, ScreeningRecord screeningRecord)
        {
            AuthenticationResult authResult = null;
            var app = App.PublicClientApp;
            var accounts = await app.GetAccountsAsync(App.PolicySignUpSignIn);

            try
            {
                authResult = await app.AcquireTokenSilent(App.ApiScopes, accounts.FirstOrDefault())
                    .ExecuteAsync();
            }

Presumably, I need to be passing in an argument that specifies the account to refresh the token for. It was my assumption that the default would be the account that is currently signed in, but this doesn't necessarily appear to be the case.

Is there documentation, or a recommended implementation for passing a specified account argument?

Example not working anymore in net 5 WPF app

Hello, we are trying to migrated our application which contains the most authentication concept from this example to .net 5 WPF (base app project built on .net framework "4.x").

In our actual app it works fine, when we migrate the app to .net 5, the registration returns always an exception (some informatons with url redirect etc...).

Also the method "WithParentActivityOrWindow" is not available in .net 5 and has to be removed from the code.

Note: #60 (closed issue) has similar issue

We have changed several code but are not able to make it run under .net 5.. We have also used for verification purpose the credential from this demo, but this also fails.

Can you update the demo code for net 5 compatibility ?

Missing Access Token

When executing AcquireTokenAsync in sample active-directory-b2c-dotnet-desktop the AccessToken is missing and IdToken is set.
Not sure if this is correct behavior.
Assuming that IdToken contains JWT, then the sample should use IdToken instead of AccessToken in following line:

ResultText.Text = await GetHttpContentWithToken(App.ApiEndpoint, authResult.AccessToken);

Last but not least, for some reason encoded token in IdToken seems not to be correct.
Getting following after decoding:

{"typ":"JWT","alg":"RS256","kid":"X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk"}�⦗炣㓓�#�#㳃₦榢#㓓�#�#Ss�₧fW"#⣒ア¦緲#⦇GG�3Ⲷƶv梦֖7&綶gF榆榒涶ҳsSc㖳&RӦS��ӆ#&B֓v#b֦S&�#V63�&�r磢ゲ"§7V"#⣦f3�F3�"֓㶢ӃsVRӃ㆒ӃS&C㶦F3S梢¦�VB#⣦3㓓��RӖcCbӆSVRӖ#�RӖ6C

Sample stuck in an infinite loop showing a blank window with 'redirecting'

We noticed this happening yesterday with our main product that uses b2c. I thought I'd try with your sample app and I get the same behaviour on a number of different machines. When I try to login, I just get a blank popup with redirecting inside it. A few things to note

(a) It's impacting our customers not just internal users
(b) It doesn't seem to happen on a clean machine (I created one in an Azure vm)
(c) It doesn't seem to happen with a new user account

The big difference that gets everything working though it to change from login.microsoftonline.com to b2clogin.com

    private static readonly string Tenant = "mytenantname.onmicrosoft.com";
    private static readonly string AzureAdB2CHostname = "mytenantname.b2clogin.com";

Authority should use b2clogin domain

The MSALv3 branch works with simple username-password login, but it gives a redirect URI error when I want to use Microsoft Account login:

invalid_request: The provided value for the input parameter 'redirect_uri' is not valid. The expected value is a URI which matches a redirect URI registered for this client application.

I have tracked down the issue to the BaseAuthority field in App.xaml.cs. It should use the new b2clogin.com domain according to the docs as the B2C Microsoft Account config also uses the b2clogin domain.

Additional information in the documentation

It would be useful to add some documentation on how to configure the URI scheme in the .NET app, which will eventually used in the production scenario as the redirect uri instead of the localhost. For example, how we can configure this com.onmicrosoft.contosob2c.exampleapp://oauth/redirect

Why does this not find my Azure account ?

This example fails to find my azure account but finds my other Microsoft accounts. What gives here ? I can log in to my azure account no problem from the azure.portal.com but this example code tells me that no account exists ?

Commonality between sign-in and API call scenarios

I'm getting started with authenticating my app with MSAL. Now I'm copying and pasting from this sample. There's redundancy, however, that I don't want to carry over to my app.

I think that acquiring a token interactively is the same whether it's upon sign-in or in response to an MsalUiRequiredException exception thrown during an API call. In my app, I'd like this to be a common GetTokenInteractively method that's called in the two scenarios.

In this sample, I notice that .WithPrompt(Prompt.SelectAccount) is called upon sign-in but not for an API call.

According to WithPrompt's docs, "The default is Microsoft.Identity.Client.Prompt.SelectAccount". So that means all the .WithPrompt(Prompt.SelectAccount) lines have no effect and can be safely removed, right? That would make the code for interactively acquiring tokens more similar between the sign-in and API call scenarios.

One remaining difference between these two scenarios in the sample app, is that the sign-in scenario handles the AADB2C90118 error to run the Forgot Password user flow. Could that also apply to the API call scenario? A user could forget her password while trying to call an API. Even if not, having that error handling code in the common method wouldn't hurt the API call scenario, right?

Update to MSAL 4

Please update the whole sample to use the new version of MSAL (4).

There are breaking changes from MSAL 3 to 4.

Persist authentication

This sample has helped me get a fairly good understanding of how to manage authenticated users and sessions on a local Windows 10 app. One thing that I would like to be able to do however, is persist the authenticated session.

Current Behavior

  • Login to application
  • Acquire id token and access token
  • Refresh access token as necessary
  • Close app -> authenticated session ends.

Desired Behavior
I would like to be able to achieve the behavior above plus be able to open the application again after closing it and still be authenticated.

Right now, authenticated session ends when I close the app. How would I go about chaining this behavior?

Id token and access token do not get the updated user info when doing AcquireTokenSilentAsync

I am doing the following steps

  1. Execute this code
var authResult1 = await app.AcquireTokenInteractive(App.ApiScopesBasic)
                   .WithUseEmbeddedWebView(false)
                    .WithParentActivityOrWindow(new WindowInteropHelper(this).Handle)
                    .ExecuteAsync();

which is in the SignInButton_Click code of this sample.
an id token is returned, which includes several claims including for example the user's first name - which right now is "name1".

  1. After the above call is done, I manually update the information of the user in the azure portal (eg. update the first name from "name1" to be "name2"). In reality, I would not update the user's info in the portal but I could have some other application updating the user's information using graph API while the user still has a valid refresh token.

  2. Do this call

var authResult2 = await app.AcquireTokenSilent(App.ApiScopesBasic, accounts.FirstOrDefault())
                        .WithForceRefresh(true)
                        .ExecuteAsync();

in the id token of this auth result, I still get the "name1" as in the call of step 1 (instead of the "name2" as updated in step 2). If instead of acquiring the token silently, I do an interactive one then I will get the correct name.

Is the .WithForceRefresh(true) not enough? How can I force get the user's latest information without requiring user interaction?

thanks

API Call Results textbox needs to cleared after successful login

steps to reproduce:

  1. Click on sign-in button
  2. Close the window
  3. Note how the "API Call Results" textbox shows how the user cancelled authentication
  4. Click sign-in and successfully sign-in

Results:
The API Call Results textbox still shows the exception from the user cancelled authentication

Expected:
Textbox to be cleared

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.