.NET Core

Blazor Authentication: Hide a Nav Menu Item

In last week’s post, Server-Side Blazor with Authentication, we covered creating a Server-Side Blazor application with Authentication and then used the attribute to not allow the user to view the Fetch data page if they weren’t logged in.

While the authorize attribute does keep the user from viewing the contents of the page it still allows the user access to the nav menu item for the page they aren’t authorized to access. This is going to be a quick post showing how the AuthorizedView component can be used to hide any content that a user should be logged in to see (or be in a specific role).

Hide a Nav Menu Item

In the Pages/Shared directory open the NavMenu.razor file which is the file where the nav menu is defined. The following code is the code that renders the Fetch data menu item which is the section we want to hide if the user isn’t logged in.

<li class="nav-item px-3">
    <NavLink class="nav-link" href="fetchdata">
        <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
    </NavLink>
</li>

To hide menu item we wrap the list item in the AuthorizeView component.

<AuthorizeView>
    <li class="nav-item px-3">
        <NavLink class="nav-link" href="fetchdata">
            <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
        </NavLink>
    </li>
</AuthorizeView>

Do note that you should still use the Authorize attribute on the page that should require authorization and not depend on the menu item being hidden keeping users from finding the page.

Wrapping Up

While the Authorize attribute is still very useful I’m sure that the AuthorizeView will be getting a lot of use in Blazor apps. AuthrozieView has the advantage of not being limited to page component.

Also, note that AuthorizeView also supports roles and policies. Make sure and check out the official AuthorizeView component docs for more details. If interested the code for the component is on GitHub.

Blazor Authentication: Hide a Nav Menu Item Read More »

ASP.NET Core Server-Side Blazor with Authentication

It has been close to a year since I did my first into post on Blazor, ASP.NET Core Basics: Blazor, and a lot has changed. The biggest thing is that it was announced that Server-Side Blazor is going to ship with .NET Core 3. This post is going to walk through creating a server-side Blazor application including authentication.

Sever-Side Blazor

What is server-side Blazor and how is it different from client-side Blazor? The quick answer is that client-side Blazor uses WebAssembly and Mono to run .NET code in the browser allowing for basically a SPA written in .NET. With Server-Side Blazor the app is executed on the server and update/processing are requested over a SignalR connection.

For a deeper dive into the differences check out the ASP.NET Core Blazor hosting models doc.

Pre-requisites

To start make sure to install at least preview 6 of .NET Core 3. Using a command prompt you can run the following command to see which versions of the .NET Core SDK are installed.

dotnet --list-sdks

The previews of .NET Core 3 can be downloaded from here. Also, make sure to use the latest preview of Visual Studio 2019.

Application Creation

I used the following command from the command prompt to create a new Blazor application using individual authentication.

dotnet new blazorserverside --auth Individual

Visual Studio also has the template available if you select the ASP.NET Core Web Application project type and about three screens in select the Blazor Server App option.

After the creation process is complete open the project in Visual Studio. At this point, if you run the application you will see the standard options to log in or register.

Requiring Auth for a Page

At this point, the application allows account creation and login, but all pages are available to all user, even if they aren’t logged in. There are multiple ways to deal with this. For this post, I’m going with the closest to what I am used to from MVC which is using an Authorize attribute. In the Pages directory open then FetchData.razor file and make the following changes to make the page require the user to be authorized. Note that this method should only be used on page components.

Before:

@page "/fetchdata"
@using BlazorAuth.Data
@inject WeatherForecastService ForecastService

After:

@page "/fetchdata"
@using BlazorAuth.Data
@using Microsoft.AspNetCore.Authorization
@attribute [Authorize]
@inject WeatherForecastService ForecastService

Now if you go to the Fetch data page without being logged in you will see a Not authorized message. This message can be customized using the AuthorizeView component. You can find more details in the docs.

Wrapping Up

It is neat seeing how far Blazor has come since I last played with it. The docs are great and the product has improved a ton. I may do a follow-up post to go more into how to use the AuthorizeView component.

Make sure to check out the official docs on Blazor authentication and authorization to get the full picture of the subject.

ASP.NET Core Server-Side Blazor with Authentication Read More »

Azure Function App Log Streaming

One of the things I have noticed while exploring Azure Function Apps is it is important to find ways to track what is going on during execution. While exploring the Azure Portal for one of my functions apps I noticed an option for steaming logs. This post is going to show how to get to the streaming logs for a Function App.

Log Streaming Location

From the Azure Portal open your Function App and select Platform features and then click the Log streaming link.

Log Streaming View

The following screenshot is from my sample App and has two different function executions listed.

Wrapping Up

For this small sample application, this feature isn’t critical, but on a larger application, it would become much more important. Log streaming is a quick way to get an idea of what is going on, but would only be one part of knowing what is going on.

Azure Function App Log Streaming Read More »

Create an Azure Function App from Visual Studio

When I started looking at Azure Function Apps in the post, Azure Functions Introduction, I used the Azure Portal to create the sample function App used in the post. On the follow-up post, Open an Azure Portal Created Function in Visual Studio, I showed how to get a portal created function to open in Visual Studio. The code download from the Azure Portal was in the csx format instead of the cs format that Visual Studio normally deals with so a lot of Visual Studio doesn’t work.

This post is going to walk through creating a new Azure Function App from within Visual Studio. My hope is that starting from Visual Studio will result in code that is more Visual Studio friendly. This post will be using Visual Studio 2019.

App Creation

Open Visual Studio and click  Create a new project on the start dialog.

On the next screen search from Azure Functions. Click on the Azure Functions item and click the Next button.

Enter a Project name, and change any other settings if needed, then click Create.

The next dialog will ask for the type of trigger to use. To match the function we created a few weeks ago on the Azure Portal we are going to use an Http trigger and click Create.

Clicking the last Create button will kick off the project creation process. When done you will have a project with a single function that will match the following inside of the file Function1.cs.

public static class Function1
{
    [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        return name != null
            ? (ActionResult)new OkObjectResult($"Hello, {name}")
            : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
    }
}

The following is the Portal created function from a few weeks ago.

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}

You will notice that the body of the two is the same. The Visual Studio version is using attributes to let Azure know the name, the trigger type, and other information that will be needed once the function is published to Azure.

Local Testing

One really neat thing about using Visual Studio for your function development is you can debug them locally. If you hit the play button (or F5) Visual Studio will launch your function locally. You will see something like the following.

Highlighted is the section listing all the Http Functions in the applications along with URLs that can be used to test them. For this example, the following URL could be used to get the response “Hello, Eric”.

http://localhost:7071/api/Function1?name=Eric

As far as I have seen so far all the normal debugging features of Visual Studio seem to work when running a function locally.

App Publication

Now that we have created and tested our Function App locally it is time to publish it to Azure. Right-click on the project file in Solution Explorer and click Publish.

On the Publish dialog, we are going to Create New and Run from package file since it is recommended (see the docs for why it is recommended). Finally, click the Publish button.

The next dialog is the configuration for the App Service that will be created in Azure. You can take the defaults and hit Create, but I always take the extra time to create a new resource group so that my samples are easy to remove when I am done with them.

Clicking the create button will start the deployment to Azure which will take a few minutes. After the deployment, you can use the Azure Portal to test your Function App. More information on running a function from the Azure Portal can be found in the Azure Functions Introduction post.

Wrapping Up

While creating a function via the Azure Portal is the fastest way to get started, I would recommend you start locally. The slightly longer getting started time it worth it for the better tooling and flexibility it provides.

Create an Azure Function App from Visual Studio Read More »

Deploy ASP.NET Core 3 Previews to Azure App Using Extensions

A few weeks ago when the post Deploy ASP.NET Core 3 Previews to Azure App Service I got an email from Jerrie Pelser who pointed out that there are extensions available for App Service that allow usage of the public previews of ASP.NET Core 3 without having to do a self-contained deployment.

In addition to Jerrie’s suggestion pajaybasu pointed out in this Reddit post that using Docker is another option. Pajaybasu also pointed out a line in the original post where I that self-contained deployments were the only option which of course was incorrect.

The first half of this post is going to be the same as the original post which covers the creation and the initial publication to Azure App Service. The last half will cover using an extension to enable the preview version of ASP.NET Core.

Sample Application

I used the following .NET CLI command to create a new ASP.NET Core application using React for its front end.

dotnet new react

After the creation process is complete open the project in Visual Studio. I highly recommend using the Visual Studio 2019 preview release when working with any .NET Core 3 applications.

Publish to App Service

In Visual Studio’s Solution Explorer right click on the project file and select Publish.

Select App Service for the publish target. Here we are creating a new app service. Next, click Publish.

The next dialog if the information about the new App Service that will be created. I took the defaults for the most part. I did create a new resource group for this application to make the resources easier to clean up in the future. I also changed the hosting plan to the free tier. Click Create to continue.

The Error and the Warning

As part of the publishing process, a browser will be opened to the address of the application. When this happens you will see an error about ANCM In-Process Handler Load Failure (if you are using IIS In-Process Hosting).

If you look back at Visual Studio you will see the following warning that your application requires the .NET Core runtime 3.0 and App Service only supports up to 2.2. Since we are going to fix this in App Service I recommend selecting Don’t perform check in the future (only this profile).

Another Fix

For this version of the fix, go to your App Service in the Azure Portal. In the menu under the Development Tools select the Extensions option.

On the next page click the Add button at the top. Click on the Choose Extension and select the ASP.NET Core 3.0 (x86) Runtime option.

Next, click Legal Terms, read the terms and if you are OK with the terms then click the OK button. You will then have to click OK on the add extension blade which will start the extension installation.

If you were to load your site at this point you would still get the 500 error. Under Settings click the Configuration and click on General settings turn Web sockets On and click Save.

At this point, your site should be working. You can also go back and turn web sockets back off and the site will continue working. I have no idea what toggling web sockets does to make everything start working, but thanks to this comment on a GitHub issue for the key to getting this working.

Wrapping Up

Hopefully, between this post and the previous one using a self-contained deployment, you won’t have any issues trying out the .NET Core 3 with App Service.

Deploy ASP.NET Core 3 Previews to Azure App Using Extensions Read More »

Azure Application Insights Overview

In the Add Application Insights to an Existing ASP.NET Core Application post from last week, we got Application Insights up and running. This week my plan was to show off some of the features of Application Insights. It turns out this is hard to do in a meaningful way when your application isn’t getting any usage. While I have next to no data for most of the screenshots I still want to point out some of the areas of Application Insights that seem like they would be very useful.

Sample Application

For the most part, the post linked above is a good starting point with the exception of instead of using a React application I switched out for a Razor Pages application. The following is the command to create a Razor Page application with auth using the .NET CLI.

dotnet new webapp --auth Individual

The reason for this change was to get more items in App Insights since Razor Pages makes a request to the server per page.

Application Dashboard

The first item I recommend you check out is the Application Dashboard. On the Azure Portal select your App Insights resource and at the top click Application Dashboard.

This link will drop you on a page that will let you see how your application is doing at a glance. This includes everything from Unique sessions and Failed requests to Average I/O rate and Average available memory.

Live Metrics Stream

From your application dashboard or the App Insights menu you if you select Live Metrics Stream you will see real-time information about Incoming Requests, Outgoing Request, Overall Health, and a list of servers your application is running on and some stats about your usage on those servers.

Investigate

As a developer, a lot of the items in the Investigate menu jump out to me as being really helpful.

For example, Failures will give you a graph of failures over your selected timeframe with a list of the failed operations and a summary of the top 3 failed response codes, exception types, and dependency failures. The following screenshot is what it looks like, but my sample application doesn’t have any failures so it may not be super helpful.

The other option I want to point out is Performance which will give you a great summary of how your application is performing with break down by operation. This operation level view is a great place to spot areas in your application that may need some perf work.

Wrapping Up

This post covered a small fraction of the value provided by Application Insights. I encourage you to give the service a try especially if you are running a .NET application and most of the value can be provided without having to make any code changes.

Azure Application Insights Overview Read More »

Add Application Insights to an Existing ASP.NET Core Application

I have been using Azure’s App Service to host the web applications I am playing around with for a few years now. The service makes it simple to get an application hosted. Today I decided to try out Application Insights which is an application performance management (APM) service provided by Azure which integrates very well with App Service. In fact, you can enable Application Insights for your App Service Application without the need to make any code changes.

This post is going to cover using an existing App Service application and enabling Application Insights. This post is assuming that you already have an Azure account. If you don’t you can sign up for a free Azure account.

Sample Application and App Service Creation

In case you don’t have an existing application in Azure App Service here is a quick walkthrough of the application I used for this post. If you have an existing application you can skip to the next section.

From the .NET CLI I used the following command to create a global.json targeting .NET Core 2.2 in the directory the application is being created in. You don’t have to do this step, but I needed it because I have .NET Core 3 preview installed and I wanted this post to target the current production release of .NET Core.

dotnet new globaljson --sdk-version 2.2.105

Next, run the following command to create a new ASP.NET Core application using the React template. Any of the templates are fine so feel free to use a different one as long as it will give you a web application.

dotnet new react

Now open the new project in Visual Studio and right-click on the project file and click Publish.

Select App Service and then click Publish.

The next dialog is all about the setup of your App Service. I took the defaults for the most part, with the exception of the Resource Group which I made sure to create one just for this application to allow for easy clean up later. When you have all your options selected click Create. Note that there is an option to setup Application Insights from this screen, but we are going to handle this on the Azure side after the fact for this post.

After the deployment is done your application should open up in a browser.

Add Application Insights from the Azure Portal

Now that we have an application running in an Azure App Service we are ready to add in Application Insights. First head to the Azure Portal and select App Services from the menu.

From your list of App Services select the one you want to add Application Insights to. From the menu select Application Insights. In the details click the Turn on site extension button to update the Application Insights extension if needed.

On the next screen select the Location where you would like the Application Insights deployed. You can tweak what will be instrumented based on the language your application is built in, I just kept the defaults. When all your selections are done click Apply.

When you click apply, you will get a warning that your site will have to be restarted. For a test application, this isn’t a big deal, but if you are on a production application you might want to do this during a slow period. Click Yes to continue.

After the process is complete click the View Application Insights data link to view your Application Insights Overview.

The overview will give you a fast overview of how your application is doing with graphs of Failed request, Server response time, Server requests, and Availability.

Wrapping Up

Hopefully, this will help you get going with Application Insights. This post didn’t cover many of the features that Application Insights provides, but should get you set up so you can explore all the features the service provides.

Add Application Insights to an Existing ASP.NET Core Application Read More »

Deploy ASP.NET Core 3 Previews to Azure App Service

I have found some time to play around with some of the features coming with ASP.NET Core 3 and I needed a place to host some of the applications I’m playing around with. Azure App Services has always been a great place for this type of thing, but as you will see in the details below it doesn’t support ASP.NET Core 3 by default currently.

This post is going to walk through creating a new ASP.NET Core 3 React application and publishing it to a new App Service with the default setting and then show you what to change to get the application to run.

Sample Application

I used the following .NET CLI command to create a new ASP.NET Core application using React for its front end.

dotnet new react

After the creation process is complete open the project in Visual Studio. I highly recommend using the Visual Studio 2019 preview release when working with any .NET Core 3 applications.

Publish to App Service

In Visual Studio’s Solution Explorer right click on the project file and select Publish.

Select App Service for the publish target. Here we are creating a new app service. Next, click Publish.

The next dialog if the information about the new App Service that will be created. I took the defaults for the most part. I did create a new resource group for this application to make the resources easier to clean up in the future. I also changed the hosting plan to the free tier. Click Create to continue.

The Error and the Warning

As part of the publishing process, a browser will be opened to the address of the application. When this happens you will see an error about ANCM In-Process Handler Load Failure (if you are using IIS In-Process Hosting).

If you look back at Visual Studio you will see the following warning that your application requires the .NET Core runtime 3.0 and App Service only supports up to 2.2.

The Fix

After dismissing the dialog above you will see a summary of the publish profile we created above. Click the Pincel next to the Framework-Dependent value for Deployment Mode.

In the dialog that pops up set the Deployment Mode to Self-Contained and select an appropriate Target Runtime for your App Service. In the case of this sample which is deployed to a Windows App Service, we are using win-x86.

Back on the publish profile summary screen click the Publish button to redeploy the application to App Service with the new settings. When the process finishes this time you should see a browser load with your application running properly.

Wrapping Up

This is a great example of the power of being able to do self-contained deployments. If this option didn’t exist then we would have no option for running .NET Core 3 applications on App Service.

Deploy ASP.NET Core 3 Previews to Azure App Service Read More »

Create React or Angular Application from Visual Studio with Authentication

Having templates that provide a good starting point for a new application is an important part of the value that is provided by Microsoft. Nothing kills progress faster than having to spend a week trying to discover the recommended way to set up a project. Thankfully template is an area that Microsoft continues to invest in.

A few weeks ago in my ASP.NET Core 3: React Template with Auth post I went over creating a React application that included auth out of the box using the .NET CLI. In this post, we are going to create an Angular application with Auth from Visual Studio.

Required Installs

As of this writing .NET Core 3 Preview 4 was just released so please make sure you have the latest preview installed. Also, make sure and install the latest preview of Visual Studio. The screenshots in this post will be from the Visual Studio 2019 16.1.0 Preview 1 release. Make sure you have at least the ASP.NET and web development workload installed.

Project Creation

Open Visual Studio and from the Get started area on the left click Create a new project.

On the next screen select the ASP.NET Core Web Application project type and click Next.

On the next screen at a minimum enter a Project name and click the Create button.

On the next screen select the template you want to use. I will be selecting Angular, but the same authentication setup will work for React or React and Redux templates. After selecting your template type on the right side of the screen under Authentication click the Change link.

Select Individual User Accounts and click OK.

After the Change Authentication dialog closes click the Create button on the template selection dialog.

After a couple of minutes, the application will be ready to go. The only other step you will need to do is to apply the Entity Framework migrations. This can be done from the .NET CLI or the first time you try to register an account in debug mode you will be prompted to apply the migrations.

Wrapping Up

I’m not sure if I am alone in this or not, but I get super excited seeing the time being invested by Microsoft in making the getting started experiences better with every release. Having authentication available out of the box for a SAP backed by an API make getting started on a project super simple.

Create React or Angular Application from Visual Studio with Authentication Read More »

Azure B2C: User Profiles

In this post, we will be adding access to user profiles using Azure B2C. We will be building on the setup used in the ASP.NET Core with Azure B2C Auth post so make sure and check it out if something in this post isn’t clear. The following is the full list of post from what has turned in to a series on Azure B2C.

ASP.NET Core with Azure B2C Auth
Azure B2C: Customize Layouts
Azure B2C: Social Logins

User Profile Flow

The first step to enabling profile access is to add the Profile editing user flow. From the menu for your Azure B2C resource select User flows.

At the top of the list of user flows click the New user flow button. This will display a list of recommended flows to add. From the list click Profile editing.

On the Create page enter a Name for your flow, select which Identity providers can use the flow, select which User attributes to collect/display, and then create the Create button. The user attributes you select will control which fields show when the user is editing their profile. Also, notice the Show more link which will give you a full list of the user attributes available on your account.

Sample Application

Back in the sample application in the appsettings.json file enter the name of the profile editing user flow from above for the EditProfilePolicyId.

"EditProfilePolicyId": "B2C_1_Profile"

Run the application and after login, the user’s name will be a link which will take them to a page where they can edit their profile information.

The following is a sample of what the profile page looks like.

Tweaking the Layout

From the screenshot, you will notice that the order of the fields wouldn’t make a lot of sense to a user. Thankfully B2C provides a way to customize the order of files, labels, control types, etc. without doing a full custom page which is also an option if you need to match an existing application’s look and feel.

From the B2C menu, select User flows and click on your profile flow. Once in your profile flow select Page layouts and then in the details select Profile edit page.

You will see something similar to the following screenshot. As you can see it allows reordering of fields, label changes, etc.

User Attributes

If the built-in user attributes don’t cover all your needs B2C does allow you to add your own attributes. From the main menu of B2C click on User attributes and you will see a list of your current attributes as well as an Add button if you need a custom attribute.

Wrapping Up

Enabling profile access was a pretty easy process and the flexibility provided with the built-in customizations is nice. I’m betting that most people will end up using a custom layout to give users a consistent experience. If you need help getting started with a custom layout check out my Azure B2C: Customize Layouts post.

Azure B2C: User Profiles Read More »