Azure B2C integration with Flutter - azure

I have created an app registration within my tenant in B2C which I would like to use in a Flutter app. I've used the flutter_appauth package in my Flutter project to access the B2C instance.
However, when attempting to run the application, I receive the following error:
I double checked my registration, and the information seems correct:
Within my Adnroid / build.grade file I have the following specified:
manifestPlaceholders = [
'appAuthRedirectScheme': 'msauth://com.parasol.app/Bmce%2B9aHdOoVtE7fS3B07tfj7Bc%3D'
]
I have attempted with just 'com.parasol.app' and 'msauth://com.parasol.app' and I receive the same issue.
Any help would really be appreciated.

The issue seems to be related to the request formation in the first place.
First off, make sure you have the following lines in your build.gradle:
defaultConfig {
manifestPlaceholders = [
'appAuthRedirectScheme': 'com.parasol.app'
]
}
As for the app registration, try creating a new app registration as per the following guide: https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-native-application?tabs=app-reg-ga with the only difference that the redirectUri should be
com.parasol.app://oauthredirect
Double check you've filled the values for clientId, discoveryUrl, scopes properly to form the request.
If you can share the code you use for calling the authorizeAndExchangeCode method with all the parameters it would help understand the issue further.

Related

Unhandled exception rendering component: Failed to construct 'URL': Invalid URL

I've followed this tutorial line by line. It's teaches how to generate a blazor wasm hosted application with all the code to authenticate with Azure B2C. All I had to do was to replace place the correct values in the right places.
dotnet new blazorwasm -au IndividualB2C --aad-b2c-instance "{AAD B2C INSTANCE}" --api-client-id "{SERVER API APP CLIENT ID}" --app-id-uri "{SERVER API APP ID URI}" --client-id "{CLIENT APP CLIENT ID}" --default-scope "{DEFAULT SCOPE}" --domain "{TENANT DOMAIN}" -ho -o {APP NAME} -ssp "{SIGN UP OR SIGN IN POLICY}"
Unfortunately, when I run it I get this error:
It's hard to tell where the problem is coming from. I googled the error but can't find any documentation on the issue.
Thanks for helping.
Edit
Here's the script that I use to create the Blazor app
dotnet new blazorwasm -au IndividualB2C --aad-b2c-instance "testb2c.onmicrosoft.com" --api-client-id "3b113bda-55d5-47eb-9d8c-5e44375f1341" --app-id-uri "https://testb2c.onmicrosoft.com/testapi" --client-id "3b9fd635-a87f-4899-ad04-9a73fc6f4e21" --default-scope "api.read" --domain "testb2c.onmicrosoft.com" -ho -o BlazorCmdLine -ssp "B2C_1_SignUpIn"
To anyone who finds themselves in this situation - instead of checking your values and running the command again, open up the appsettings.json file and check the "AzureAdB2C.Authority" value. It should be a valid URL in the format: "{AAD B2C INSTANCE}/{TENANT DOMAIN}/{SIGN UP OR SIGN IN POLICY}"
Example:
"https://testb2c.b2clogin.com/testb2c.onmicrosoft.com/B2C_1_SignUpSignIn"
Source: https://learn.microsoft.com/en-us/aspnet/core/blazor/security/webassembly/standalone-with-azure-active-directory-b2c?view=aspnetcore-5.0
There were 2 real problems related to the lack of attention.
I used the same value testb2c.onmicrosoft.com for both the {AAD B2C INSTANCE} and the {TENANT DOMAIN}.
{AAD B2C INSTANCE} Instance should be https://testb2c.b2clogin.com/
{TENANT DOMAIN} domain should be testb2c.onmicrosoft.com
I forgot to add a forward slash at the end of the {AAD B2C INSTANCE} Instance. So I was getting "Authority": "testb2c.onmicrosoft.comtestb2c.onmicrosoft.com/B2C_1_SignUpIn",
Thank you, #just the benno, #Carl Zhao, and #Allen Wu
Make sure appSettings.json file is included when building/running your solution.
appSettings.json will contain configuration values of your Azure AD B2C similar to the following:
{
"AzureAdB2C": {
"Authority": "https://contoso.b2clogin.com/contoso.onmicrosoft.com/B2C_1_signupsignin1",
"ClientId": "4369008b-21fa-427c-abaa-9b53bf58e538",
"ValidateAuthority": false
}
}
Double-click your project in the Solution Explorer in Visual Studio to open the .csproj file.
In my case the .csproj file contained an ItemGroup saying to never include appSettings.json during debugging or running of the app:
<ItemGroup>
<None Include="appSettings.json" CopyToOutputDirectory="Never" ExcludeFromSingleFile="true" CopyToPublishDirectory="Never" />
</ItemGroup>
I commented the entire item group and saved the .csproj, ran the app and I could successfully authenticate.

Problems authenticating with MSAL and Azure B2C in a Xamarin.Forms app

I'm having some difficulty getting one of the sample Xamarin.Forms/Azure applications to work with my own Azure B2C tenant, specifically active-directory-b2c-xamarin-native.
I was able to get the sample to work out of the box, my only change being to update all the XF NuGet packages. At this point both the Android (on my Google Pixel) and UWP versions worked perfectly; on iOS I was able to log in/out and edit the profile (it still has the known issue that iPhoneSimulator doesn't properly save tokens in the keychain, so the API and caching doesn't work, but i'm ignoring that for now until i can get an actual iPhone). The problems started when I tried to set up and use my own B2C tenant, according to the instructions in the readme file. Since the original sample works, it's safe to assume that the code is ok; the only changes I made were to the magic strings at the top of App.cs, and the redirect URI's stored in AndroidManifest.xml and Info.plist. So the working theory is that I either entered one of those strings wrong, or the B2C setup is wrong. I've gone over this multiple times now and I can't find the issue. I'm willing to bet these are all caused by the same mistake on my part, though.
Problem 1 (solved). UWP app does not allow login. Instead when the embedded browser opens I get the message "We can't connect to the service you need right now. Check your network connection or try this again later", followed by an "MsalException: WAB authentication failed" dialog once I dismiss the browser.
This was the only issue I was able to fix so far, either by commenting out this line in the UWP.MainPage constructor:
UserDetailsClient.Core.App.PCA.RedirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString();
or by adding the value returned by that GetCurrentApplicationCallbackUri() call (which is something like "ms-app://s-1-15-2-900855338....") to the Custom Redirect URI list of the UI app in B2C. I would prefer simply removing the line of code, but that begs the question as to why that line of code was needed in the first place. Perhaps someone can suggest why using the ms-app:// redirect on the backend might be preferable to the msalXXXX://auth used by the other platforms. I have no idea why the original sample worked with the ms-app:// redirect; perhaps that string is actually constant across all apps and is already defined in the sample's B2C tenant.
Problem 2. Having gotten past the UWP login issue now everything works on that platform EXCEPT for the API call. I get a 401 Unauthorized.
The API code is taken straight from the tutorial Develop Cloud Connected Mobile Apps with Xamarin and Microsoft Azure; it's just the backend from Chapter 1, with the [Authorize] attribute added to the TodoItemController. (All of the Chapter 1 code works, btw) App Service Authentication is still turned off on the API itself (not the B2C tenant) in Azure. If I remove the Authorize attribute from the TodoItemController, it works, provided I also pass in the additional header ZUMO-API-VERSION=2.0.0. Adding the header does not help with the 401, though.
Since I'm able to login, I'm guessing I have a valid access token, it's just not what the backend is expecting. Again, this works on the sample, so I don't know how my app differs. I suspect this issue also affects iOS and Android, but I'm not sure because unable to complete the login on those platforms. Which brings me to...
Problem 3. On Android & iOS, on clicking SIGN IN the app opens the system browser and I'm able to login in, but the subsequent redirect doesn't happen and the app remains in it's initial state. When debugging, the line after the call to App.PCA.AcquireTokenAsync() is never reached. No exception is raised.
From what I understand this is generally due to either the redirect URI being improperly formed or forgetting to add the platform-specific redirect code (intent-filter on Android, or OpenUrl on iOS). I've double-checked the URI a half-dozen times, and the code has to be correct since the sample worked. I did notice the ActivityManager START entry in the Android logcat, so the browser is sending the redirect, but the app isn't responding to it for whatever reason. Note also that the UWP client DOES work using that same msalXXXX://auth URI (this is why I bothered to explain problem 1 above)
Visual Studio 2017 15.8.6
Xamarin.Forms 3.2.0.871581
Microsoft.Identity.Client 1.1.4-preview
Below is the list of strings from App.cs, as well as screenshots from my B2C setup. Any help would be greatly appreciated!
public static string Tenant = "myapp.onmicrosoft.com";
public static string ClientID = "d43c8xxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";
public static string PolicySignUpSignIn = "B2C_1_emailPolicy";
public static string PolicyEditProfile = "B2C_1_profileEditPolicy";
public static string PolicyResetPassword = "B2C_1_passwordResetPolicy";
public static string[] Scopes = { "https://myapp.onmicrosoft.com/api/read" };
public static string ApiEndpoint = "https://myapp.azurewebsites.net/tables/todoItem";
public static string AuthorityBase = $"https://login.microsoftonline.com/tfp/{Tenant}/";
public static string Authority = $"{AuthorityBase}{PolicySignUpSignIn}";
public static string AuthorityEditProfile = $"{AuthorityBase}{PolicyEditProfile}";
public static string AuthorityPasswordReset = $"{AuthorityBase}{PolicyResetPassword}";

Azure Web App - Cannot GET (particular path)

I have been trying out the AADv2 sample from BotAuth to no avail.
The error that I keep getting after I select the button on the action card is that either a HTTP 500 internal server error, or Cannot GET /botauth/aadv2. When I check if the root web page or the messaging endpoint is working or not, I get the same error - either Cannot GET / or Cannot GET \api\messages. The root page I have been trying to get to is https://(botname).azurewebsites.net
May I know what steps I can take to resolve this issue? I have tried to Google the error, but to no avail. Please let me know if you need more information!
Since you are test the sample directly on Azure Web Apps, there should be a few of questions we should pay attention on.
1, const MICROSOFT_APP_ID = envx("MICROSOFT_APP_ID");
const MICROSOFT_APP_PASSWORD = envx("MICROSOFT_APP_PASSWORD");
we declare the environment valiable as MicrosoftAppId and MicrosoftAppPassword. Please modify this sentence as
//bot application identity
const MICROSOFT_APP_ID = envx("MicrosoftAppId");
const MICROSOFT_APP_PASSWORD = envx("MicrosoftAppPassword");
2, And you also need to check the environment variables are set correctly in Application settings of Azure Web App, which is shown at https://github.com/MicrosoftDX/botauth/tree/master/Node/examples/aadv2#3-setup-environment-variables
3, You can leverage online code editor to develop, debug, and manage your project on Azure Web Apps.
And in the output column, you can see the detailed errors throwm by the application. You can leverage these info to narrow down your issue.
Tips, after you changing the application settings, it's better to restart your Azure Web App.

Swagger not working on Azure Web app running as OWIN

I have a ASP.NET Web API implemented as OWIN middleware. I hosted it on azure and now I have a problem using swagger. It is perfectly working on localhost but when I try it on azure I get this:
The way I did my configuration for swagger on the API was to completely remove SwaggerConfig.cs file and add all the configuration into my Startup.cs class as shown here: How to generate documentation using swashbuckle for WebApi 2 with Owin . If it is going to help, I am trying to implement oAuth2 between my API, identity server and client application.
Can you help me find out what is the reason for not getting swagger functionality on Azure?
EDIT: I also tried the solution from here but without success. I went to my API->Properties->Buld tab->Changed to 'Release' configuration->In the output path added the same what was in the 'Debug' configuration and nothing.
My bin folder on Azure:
I had this problem myself when going though this tutorial.
In that tutorial on #3 under "Configure the middle tier to call the data tier" I named my key apiAppURL instead of toDoListDataAPIURL. This caused me to get 500 response codes and
{
"Message": "An error has occurred."
}
in the response body.
I fixed it by updating the following line:
var client = new ApiApp(new Uri(ConfigurationManager.AppSettings["toDoListApiURL"]));
to
var client = new ApiApp(new Uri(ConfigurationManager.AppSettings["apiAppURL"]));
**The change made was to the string at the end of the line. That code can be found in ToDoListController.cs on line 42
Hope this helps someone!
Check your SwaggerConfig.cs file, if you are not included the xml file with your swagger, it works in your azure app services.
c.IncludeXmlComments($#"{System.AppDomain.CurrentDomain.BaseDirectory}\bin\WebApiSwagger.XML");
c.DescribeAllEnumsAsStrings();
I've included these 2 lines of code to show my xml in the swagger, the azure swagger will gone error.
This is late reply but may help someone in future.
I solved this issue this way:
Set XML documentation file path in project settings to : wwwroot\api.xml
Let Swagger know where the file is within ConfigureServices method in
Startup.cs:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
// Set the comments path for the Swagger JSON and UI.
var xmlFile = "api.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, "wwwroot", xmlFile);
c.IncludeXmlComments(xmlPath);
});
You can set different paths but you will get the idea of how to do it from this example.

Azure Auth error: Multiple types were found that match the login provider named 'facebook'

I'm running into an error when trying to authenticate a user via Facebook using the Azure Mobile Services built in APIs. I've looked through my packages and can't see any reason why I'd have two providers as suggested in the error:
Multiple types were found that match the login provider named
'facebook'. This can happen if multiple login providers are defined
with the same name but different casing which is not supported. The
request for 'facebook' has found the following matching login
providers: Facebook Facebook.
I did create a branch that upgraded to the App Services and then reverted back to AMS instead. I'm wondering if something is lingering which is causing the problem.
My package list is as follows:
Autofac{3.5.2}
AutoMapper{3.2.1}
EntityFramework{6.1.1}
Microsoft.ApplicationInsights{1.0.0}
Microsoft.ApplicationInsights.Agent.Intercept{0.17.0}
Microsoft.ApplicationInsights.DependencyCollector{1.0.0}
Microsoft.ApplicationInsights.JavaScript{0.11.0-build09387}
Microsoft.ApplicationInsights.PerfCounterCollector{1.0.0}
Microsoft.ApplicationInsights.Web{1.0.0}
Microsoft.ApplicationInsights.Web.TelemetryChannel{1.0.0}
Microsoft.AspNet.Cors{5.2.2}
Microsoft.AspNet.Identity.Core{2.0.1}
Microsoft.AspNet.Identity.Owin{2.0.1}
Microsoft.AspNet.Razor{3.2.2}
Microsoft.AspNet.WebApi.Client{5.2.2}
Microsoft.AspNet.WebApi.Core{5.2.2}
Microsoft.AspNet.WebApi.Cors{5.2.2}
Microsoft.AspNet.WebApi.OData{5.2.2}
Microsoft.AspNet.WebApi.Owin{5.2.2}
Microsoft.AspNet.WebApi.Tracing{5.2.2}
Microsoft.Data.Edm{5.6.2}
Microsoft.Data.OData{5.6.2}
Microsoft.Data.Services.Client{5.6.2}
Microsoft.Owin{3.0.0}
Microsoft.Owin.Host.SystemWeb{3.0.0}
Microsoft.Owin.Security{2.1.0}
Microsoft.Owin.Security.ActiveDirectory{2.1.0}
Microsoft.Owin.Security.Cookies{2.1.0}
Microsoft.Owin.Security.Facebook{2.1.0}
Microsoft.Owin.Security.Google{2.1.0}
Microsoft.Owin.Security.Jwt{2.1.0}
Microsoft.Owin.Security.MicrosoftAccount{2.1.0}
Microsoft.Owin.Security.OAuth{2.1.0}
Microsoft.Owin.Security.Twitter{2.1.0}
Microsoft.WindowsAzure.ConfigurationManager{2.0.3}
Newtonsoft.Json{6.0.4}
Owin{1.0}
RazorEngine{3.4.1}
Sendgrid{6.1.0}
SendGrid.SmtpApi{1.3.1}
System.IdentityModel.Tokens.Jwt{3.0.2}
System.Spatial{5.6.2}
WindowsAzure.MobileServices.Backend{1.0.470}
WindowsAzure.MobileServices.Backend.Entity{1.0.470}
WindowsAzure.MobileServices.Backend.Storage{1.0.470}
WindowsAzure.MobileServices.Backend.Tables{1.0.470}
WindowsAzure.ServiceBus{2.3.4.0}
WindowsAzure.Storage{3.1.0.1}
Is there anything here which could be causing the issue?
Having compared with an older version of the project, it looks to not be related at all to my packages. Instead the problem was caused by adding the login provider within the WebApiConfig class.
Removing the following resolved the issue:
options.LoginProviders.Add(typeof(FacebookLoginProvider));

Resources