Firebase CLI provides a cloud function emulator which can be used to run the Firebase Cloud Function locally before deploying to production. Following are the types of functions which can be emulated.
HTTP functions
Callable functions
Background functions triggered from Authentication, Realtime Database, Cloud Firestore, and Pub/Sub.
We will test a simple http function which we created in the last post.
Firebase emulator is included in Firebase CLI, so we need to install it, or update it to the latest version.
npm install -g firebase-tools
Setting Up Admin Credentials for Emulated Functions
If your cloud function requires interaction with Google API or Firebase API via the Firebase Admin SDK then you may need to setup the admin credentials.
The Firebase emulator, which is included in the Firebase CLI, let’s us test the function locally before deploying to the cloud.
In this post we started with installing Firebase CLI and then we setup the Google Account Credential. Google Account Credential requires a JSON file with private key, which was generated in the Google Cloud Platform. Then we started the Firebase emulator and browsed the local function URL and received response from the local function.
Hope you liked this, please share your feedback or any query.
Firebase cloud functions let’s you run a piece of code in cloud without managing the servers. This is quite helpful when you just want to manage your code and not to worry about the servers executing the code. This pattern is also known as serverless architecture.
These cloud functions can be triggered by multiple events such as an http request, scheduled time or in response to changes in Realtime Database and perform the intended job.
In this post we will see how we can create a simple Firebase cloud function using Firebase CLI and then deploy it to Firebase. We will use TypeScript to write the function.
Let’s create and deploy a Firebase cloud function.
Installing Firebase CLI
Firebase cloud functions are created and deployed using Firebase CLI, so let’s install the Firebase CLI globally. Type following command on command prompt.
npm install -g firebase-tools
Login to Firebase CLI
We need to authenticate to Firebase to create and deploy cloud functions, authenticate to Firebase using following command.
firebase login
This will open a browser window to authenticate.
If you are logged in with another account then you can logout first using following.
firebase logout
Choose the account to login.
Allow, to grant permissions to Firebase CLI.
On Allow following success screen will be presented.
And in command prompt message like following will be logged.
Creating a Firebase Cloud Function Project
Create a directory for the project.
mkdir firebase-function-demo
Change to project directory.
cd firebase-function-demo
Open the directory with Visual Studio code or any other editor.
code .
Initialize Firebase functions project
firebase init functions
Accept the confirmation.
Choose the appropriate option for you. In my case I chose “Use an existing project“, because I have already created the Firebase project.
Next I chose the project from the presented list.
For this example we are going to use the TypeScript, so choose the TypeScript.
Choose Y if you want to use ESLint.
Select Y to install the dependencies.
Your project structure should appear like this so far.
Creating a Cloud Function
We will use the sample helloworld cloud function created by the Firebase CLI for this example.
Open selected index.ts.
index.ts contains commented sample function.
Uncomment the code, and save the file.
File contains one sample http request based cloud function. Which will log following.
"Hello logs!", {structuredData: true}
and return following response.
"Hello from Firebase!"
In the same file more functions can be added, for example we can add another scheduled function like following.
export const scheduledJob = functions.pubsub.schedule("every 5 minutes")
.onRun(()=>{
console.log("This will be run every 5 minutes.");
return null;
});
This scheduled function will run every five minutes,
cron expression can be added like following to define trigger time for scheduled functions.
export const scheduledFunctionCrontab = functions.pubsub.schedule('5 11 * * *')
.timeZone('America/New_York') // Users can choose timezone - default is America/Los_Angeles
.onRun((context) => {
console.log('This will be run every day at 11:05 AM Eastern!');
return null;
});
Deploying cloud function
Let’s deploy the sample code in index.ts to cloud.
Execute the following command on command prompt.
firebase deploy
On successful function deployment, function url will be provided.
Paste the URL in the browser.
and you will get the response like below from cloud function.
Great! Our cloud function is successfully deployed and responding to http request.
Navigate to Firebase project and select functions.
and you should be able to see your cloud function.
You can switch to Logs tab to see the logs of the cloud function.
Congratulations! We have just deployed our first simple cloud function.
Conclusion
In this post we learned how we can create a Firebase Cloud Function and deploy to Firebase. We started with how to install the Firebase CLI globally, and how to authenticate to it. Then we created a template project for cloud function using Firebase CLI and then deployed and tested the cloud function.
Azure Active Directory B2C enables users to authenticate themselves to applications using local accounts or social accounts such as Google, Facebook or LinkedIn.
The applications leveraging the Azure AD B2C, don’t have to maintain the authentication mechanism. All of that complexity will be handled by Azure AD B2C.
In this post we will see how to configure Azure AD B2C from scratch for ASP.NET Core applications.
We will go through the following topics:
Creating a new Azure AD B2C Tenant
App registration in Azure AD B2C Tenant
Configuring User Flows
Creating ASP.NET Core Web application Using Visual Studio 2019 and Configuring Azure AD B2C
Creating ASP.NET Core Web application Using .NET CLI and Configuring Azure AD B2C
To configure the Azure AD B2C for the applications first we need to create the Azure AD B2C tenant. Let’s create a new Azure AD B2C tenant.
Creating a New Azure AD B2C Tenant
To create a new Azure AD B2C tenant, login to your Azure portal and click on Create a resource.
In Create a resource page search for Azure Active Directory B2C in the search box, and select the first option available as shown below.
You will be navigated to Azure Active Directory B2C resource page.
Click on Create to create the Azure AD B2C tenant. This will create a separate tenant from your Azure AD tenant.
In the next screen you will be presented with following two options:
Create a new Azure AD B2C Tenant.
Link an existing Azure AD B2C Tenant to my Azure subscription.
Let’s choose Create a new Azure AD B2C Tenant to create a new tenant.
Next enter the following details for the new tenant.
Organization name: provide an organization name.
Initial domain name: provide a unique initial subdomain name.
Note down this initial domain name, we will need this to update in ASP.NET appsettings.json.
Country/Region: Select the country/region closest to your customers.
Subscription: Select subscription for your Azure AD B2C tenant.
Resource group: Choose resource group to contain Azure AD B2C tenant.
Then click on Review + Create
Validation screen will be presented.
Click on Create
You may encounter the following error.
The subscription is not registered to use namespace ‘Microsoft.AzureActiveDirectory’. See https://aka.ms/rps-not-found for how to register subscriptions.
If you get this error then check the following post how to fix this error and then continue from here.
After fixing the error try creating Azure AD B2C Tenant again, and should be successful this time. You should be able to see the status under notifications.
Go to your newly created Azure AD B2C Demo tenant.
App Registration
Any application which needs to authenticate using Azure AD B2C, requires app registration in Azure.
Let’s register an app for our ASP.NET core application.
Click on New registration button inside the App registrations under our newly created Azure AD B2C tenant.
Fill in the details for the app registration
The display name: Enter any display name to easily identify the app.
Supported account types: choose “Accounts in any identity provider or organizational directory (for authenticating users with user flows)”
Redirect URI: Select Web in dropdown and enter following url in text box
https://localhost:5001/signin-oidc
Note the port no. we have provided 5001, you may need to update according to your application port no., we will see later in this post where in ASP.NET core application port can be configured.
Register the application.
In few seconds the app will be registered and you will be redirected to your App.
Note down the Application (client) ID, we will need this to update in ASP.NET core web application’s appsettings.json file.
Authentication options
Next we need to configure the authentications options.
Select the Authentication blade from left menu in registered app and check the two authentication options as shown below and click on Save.
We have successfully configured the app now.
Next we need to configure the User Flows for Sign up/ Sign in forms.
Configuring User Flows
User flows defines the sign up / sign in process for the applications but managed in Azure AD B2C. We can configure what data will be collected from the user and passed to the application.
To configure the User Flows, go back to the Azure AD B2C tenant and click on User Flows in left navigation.
Then click on New user flow
Selecting User Flow Type
In the new User Flow we get multiple options to configure, such as Sign up, Sign in, Profile editing.
Select the Sign up and sign in for this tutorial, this will enable the sign up and sign in experience for our web application.
On selecting Sign up and Sign in, it will enable another two options. Keep default and Click on Create
In the next screen provide a name for the User Flow and select email signup.
We can configure the Multifactor authentication as well, but leave default for now.
Scroll down a bit and select Show more…
On clicking show more, multiple fields will be presented to choose from in two columns Collect Column and Return Column.
Collect Column: Collect column shows what data will be collected from the user.
Return Claim: Return claim show what claims will be passed back to the application.
Select following options for our application and then click OK.
Note we have selected Display Name in collect attribute, during sign up user will be asked for Display Name.
Click on Create.
User Flow will be created and will be available under User flows.
Creating ASP.NET Core Web Application Using Visual Studio 2019 and Configuring Azure AD B2C
Let’s create an ASP.NET core application, and then we will configure it for Azure AD B2C authentication.
Open Visual Studio and select on Create a new project.
Select ASP.NET Core Web App (Model-View-Controller) for this example and click on next.
Provide project name and location, and select Next.
Select Microsoft Identity Platform from Authentication Type and click on create.
You may be presented with following screen to install required components (dotnet msidentity pool), select Finish to install.
ASP.NET application will be created.
Updating Azure AD B2C configurations
Open the appsettings.json you will see the following configurations.
{
/*
The following identity settings need to be configured
before the project can be successfully executed.
For more info see https://aka.ms/dotnet-template-ms-identity-platform
*/
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "qualified.domain.name",
"TenantId": "22222222-2222-2222-2222-222222222222",
"ClientId": "11111111-1111-1111-11111111111111111",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Replace it with following and replace {Initial Domain Name} and {Application (Client) Id} with values we noted earlier.
{
/*
The following identity settings need to be configured
before the project can be successfully executed.
For more info see https://aka.ms/dotnet-template-ms-identity-platform
*/
"AzureAd": {
"Instance": "https://{Initial Domain Name}.b2clogin.com/",
"ClientId": "{Application (Client) Id}",
"Domain": "{Initial Domain name}.onmicrosoft.com",
"SignedOutCallbackPath": "/signout/B2C_1_susi",
"SignUpSignInPolicyId": "b2c_1_susi",
"ResetPasswordPolicyId": "b2c_1_reset",
"EditProfilePolicyId": "b2c_1_edit_profile",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Updating application Port no.
Remember earlier we specified port no. 5001 in Azure for callback Url?
Let’s update this in our ASP.NET project.
Open Properties > launchSettings.json
Update sslPort no. to 5001.
"sslPort": 5001
If you want to keep another port no. then make sure you update in Azure AD B2C app registration too.
Testing Azure AD B2C
Press F5 and you will be redirected to {orgname}.b2clogin.com for authentication, If not then click on Sign in link on web portal.
Click on Sign up, and you will be asked for sing up details along with Display name we configured earlier in User Flow.
Creating ASP.NET Core Web application Using .NET CLI and Configuring Azure AD B2C
Open command prompt.
Create a directory for the web application.
mkdir AzureADB2CCodeDemo
Switch to the directory just created.
cd AzureADB2CCodeDemo
Create new dotnet mvc application project with Azure AD B2C option, i.e. IndividualB2C
dotnet new mvc --auth IndividualB2C
Open the project with Visual Studio Code.
Code .
Open appsettings.json, you will see similar options as we saw previously with Visual Studio 2019.
Replace it with following and replace {Initial Domain Name} and {Application (Client) Id} with values we noted earlier.
{
/*
The following identity settings need to be configured
before the project can be successfully executed.
For more info see https://aka.ms/dotnet-template-ms-identity-platform
*/
"AzureAd": {
"Instance": "https://{Initial Domain Name}.b2clogin.com/",
"ClientId": "{Application (Client) Id}",
"Domain": "{Initial Domain name}.onmicrosoft.com",
"SignedOutCallbackPath": "/signout/B2C_1_susi",
"SignUpSignInPolicyId": "b2c_1_susi",
"ResetPasswordPolicyId": "b2c_1_reset",
"EditProfilePolicyId": "b2c_1_edit_profile",
"CallbackPath": "/signin-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
Updating application Port no.
Let’s update the port for project generated from .NET CLI.
In this post we learned how to configure Azure AD B2C for ASP.NET Core applications to allow users to authenticate themselves leveraging Azure AD B2C capabilities. Azure AD B2C let’s users to use local account or social accounts such as Google, Facebook or LinkedIn for authentication.
We started by setting up the new Azure AD B2C tenant and registered app for ASP.NET core application. Then we configured User Flow for Sign up and Sign In. Next we configured Azure AD B2C settings in ASP.NET core applications created using Visual Studio 2019 UI and .NET CLI.
Please leave your feedback or any queries you have.