Pass ASP.NET Core Appsettings Values to Angular via an API Call

There have been a few issues opened on the repo I have showing usage of Angular, Identity Server 4, and ASP.NET Core together that related to incompatibilities with the newer versions of Angular. In an effort to fix this issue the plan was to recreate the client application using the new Angular template from Microsoft which from what I read should address the issue.

The code before any changes can be found here, but in this case, the whole client application has been recreated so the starting point may not be super helpful.

The Problem

For the most part, this worked well, but the problem can when I needed to use some configuration values from ASP.NET Core in my new Angular application. The previous versions of the template used server-side rendering which I utilized to pass the configuration values. The new template doesn’t use server-side rendering by default and I wanted to find a way to solve the issue without requiring server-side rendering.

The other issue is that I want to be able to run this application in Azure and set the configuration values as environment variables. While Angular seems to have support for environment files finding a solution that used a systems environment variables turned out too not be simple.

Configuration API Endpoint

Since the configuration values I need to get to the client application are secret I decided to go the route of pulling them via an API call back to the same ASP.NET Core application that is hosting the Angular Application, which is the Client App project in the sample solution.

I added a  ConfigurationController.cs class to the  Controller directory with the following contents.

This controller gets constructed with a reference to the application’s configuration which is then used to populate a dictionary with the values my Angular application needs. For completeness, the following is the contents of the application’s  appsettings.json file.

Angular Changes

This is the part that I really struggled to get right. I needed the configuration values from the API above to be available as soon as possible. Thankfully I came across this blog post by Juri Strumpflohner which covers using Angular’s  APP_INITIALIZER.

The first thing I need was to create a class in Angular to get the configuration values from the API and serve to them the rest of the Angular application. To do this I added a  configuration.service.ts into a new  ClientApp/src/app/configuration directory. The full class follows.

This class hits the API to get the configuration values in the loadConfig function and maps it to a class level field. It also provides properties to get the individual configuration values.

As I mentioned above, getting the application to get these configuration values in a timely matter was something I really struggled to do. The first step to using Angular’s  APP_INITIALIZER to solve this issue is to change the import from  @angular/core to include  APP_INITIALIZER and to import the  ConfigurationService.  All these changes are being made in the  app.module.ts file.

Next, we need to define a function that will call the  ConfigurationService.loadConfig function.

Finally, in the  providers array add an element for the  APP_INITIALIZER and the  ConfigurationService.

 Wrapping Up

This is one of those things that turned out to be way more complicated than I expected. Thankfully with the above changes, I was able to get it working. I hope this saves you all some time. The code with all the changes can be found here.

Two-factor Authentication in ASP.NET Core 2

This post was going to be an update of the SMS using Twilio Rest API in ASP.NET Core post a made a year or so ago, but once I got the example project created I noticed that the default template has removed SMS as an option for two-factor authentication in favor of authenticator auth support.

This post is going to explore the setup of this new two-factor authentication style. In a follow-up post, I may look at adding back support for SMS as the second factor as that seems like a more common scenario albeit a less secure one.

Project Setup

To create a new Razor Pages application using individual authentication I used the following command from a command prompt. Make sure you are in the directory you want the files to end up. The only reason I mention this is I just spend the last 5 minutes cleaning up my user directory because I forgot to change directories.

Next, I move up a directory and used the following command to add a new solution file.

Finally, I used the following command to add the new project to the solution file. If you aren’t using Visual Studio then you don’t have to have the solution file.

The project after the above can be found here.

Add a QR Code

Strictly speaking, a QR code isn’t required, but it is much better for users so they don’t have to enter a 32 character key into their authenticator application manually. I followed the official docs to enable QR code generation.

The first step is to download a Javascript QR Code library. I just used the one recommended in the docs, but any would work. This link will take you to a zip download. Open the download and copy  qrcode.js and  qrcode.min.js into a new  qrcode directory inside of your project’s  wwwroot/lib/ directory.

Next, find your project’s  EnableAuthenticator.cshtml file and update the scripts section at the bottom of the page to the following.

Enabling Two-Factor Authentication

The above changes are all that is required, and now we are going to walk through what it looks like for the user. Once logged in click on your user in in the upper right after of the site to open user management.

Next, click the Two-factor authentication link.

Then, click Configure authenticator app link.

This will land you on the page with the QR code.

Now using the authenticator application of your choice you can scan the QR code. Once scanned your authenticator application will display a code. Enter the code in the Verification Code box and click Verify. If all goes well you will be taken to a page that lists a set of recovery code for use if you can’t use your authenticator application for some reason.

Wrapping Up

I think it is awesome how easy the ASP.NET Core team has made the use two-factor authentication. With this being built into the templates it pushes all in the right direction. I do wish they would have left SMS as an option, but hopefully, it wouldn’t be hard to put back in.

The code in the final state can be found here.

ASP.NET Core 2 Fails to Publish With Angular 5

I had an issue opened on my Identity Server GitHub repo saying that publishing the client application fails with something like the following error when using server-side rendering.

Can’t resolve ‘./../$$_gendir/ClientApp/app/app.module.browser.ngfactory’

This was only an issue after moving the project to target Angular 5. After some research, it turns out that Angular tools for Webpack has to use a different plugin for ahead of time compiling for Angular 5+. I ended up finding a fix in this issue.

The Fix

In order to resolve the issue, I made the following changes in the  webpack.config.js file. The first change is in the require statements at the top of the file.

Next, make the following replacement in the rest of the file, which should only be two places.

Wrapping Up

Most of the projects I reference on this blog are written to specifically target the topic I am trying to cover and as such I miss things like testing publish since I’m never going to production with these applications. I really appreciate those of you who find issues and take the time to open an issue on GitHub. Keep them coming, and if you find a solution before I do feel free to submit a pull request.

 

Trying the New ASP.NET Core Angular Template with CLI Support

I got hit by the flu that has been going around and now that the fever has passed I thought it would be a good time to try out the new version of the Angular template for ASP.NET Core that works well with the Angular CLI.

Template Installation

Note that at the time of this writing the templates are in the release candidate stage and a new version could be available by the time you are reading this so make sure and check this page for potential updates.

Running the following command from a command prompt will install the RC version of the templates.

Project Creation

Create a directory for the project and navigate to it in a command prompt. Run the following command to create the new Angular project.

Next, if you have a solution you want to add the new project to that can be done with the following command adjusting for the naming of your project and solution.

Installation of Angular CLI

From the command prompt run the following command to install the Angular CLI globally.

After the above, I got the following error trying to run any Angular CLI commands.

You seem to not be depending on “@angular/core”. This is an error.

The problem ended up being that I had not installed all the packages for the project. The issue was cleared up by the following command.

Angular CLI Usage

Navigate to the ClientApp directory and you can then use all the Angular CLI commands as you would in a stand along Angular application. Some of which can be found here. If you are looking for a quick command to verify all is work the following command works well by running a linter on your project.

Wrapping Up

Having templates that are compatible with the Angular and React CLI is a big step forward. The CLIs provide a lot of functionality and by having a setup that doesn’t restrict their usages is a great move. Make note that server-side rendering is no longer enabled by default, but can still be enabled for Angular projects, but not React based projects.

I recommend you check out the official documentation which can be found here.

I hope we see these functionality moves to the other templates that are outside of the templates in this package in order to support Aurelia and Vue.

Change ASP.NET Core from npm to Yarn

Over the past couple of months, I have been having some issues with npm. Between the upgrading of npm Windows begin a pain and a version incompatibility with node I have just gotten frustrated with it. This post is going to cover the steps to use Yarn as a replacement for npm in an ASP.NET Core application.

Installation

The first step is to get Yarn installed. Head over to this site and download and run the installer for your operating system.

For Visual Studio, Mads Kristensen created an extension for Yarn that makes the integration much better. The installer for the extension can be downloaded from here.

Conversion

Open a command prompt in the same directory as your project’s  package.json file and run the following command.

This will create a  yarn.lock and lay out the  node_modules folder using Yarn’s resolution algorithm.

I did hit the following error when I did the  yarn command. I left out the specific file that it had an issue with because I am sure yours would be different.

To clear the issue I just deleted the  node_modules directory and let Yarn recreate it. It might also work to use a command prompt with administrator privileges.

Visual Studio

With the Yarn extension installed there are a couple of settings that are helpful to change. All the setting we will be changing can be found under the Tools > Options menu. The first is to have  yarn install run when the  package.json is saved. Look under  Web > Yarn Installer for this option.

The second setting is to turn off automatic NPM restore so packages are restored twice. This requires the options under NPM to be set to false. The options can be found in  Projects and Solutions > Web Package Management > Package Restore.

The extension helps with Yarn integration, but the integration still isn’t as full-featured as using NPM. At my current level of frustration having to manually restore package when I open a project on a new PC is totally worth it.

Wrapping Up

So far Yarn has been great and I have not hit any issues, but my usage has also been limited. It seems like a solid alternative to NPM.

Make sure and check out Yarn’s official post on migrating from NPM which can be found here. Of specific interest will be the CLI command comparison which can be found here.

Auth0: Usage from Angular

This post is a continuation of my exploration of using Auth0 with ASP.NET Core with an API and an Angular front end. I recommend you start with the first post if you are new to Auth0.

This post is going to add a login from Angular in the Client Application as well as accessing the API once logged in. The starting point of the code can be found here.

API Application

To give us an endpoint in the API to call let’s move the  SimpleDataController class from the  ClientApp/Controllers directory to  ApiApp/Controllers directory. Also, remember to adjust the namespace to reflect this move.

To remove some complication we are going to add a CORS policy to the API Application to allow all CORS request. This wouldn’t necessarily something I would recommend for a production application. For more information on CORS check out this post.

To add the CORS policy open the  Startup class and add the following to the  ConfigureServices function which adds a CORS policy to DI that allows all calls through.

Next, in the  Configure function, CORS needs to be added to the HTTP pipeline with the policy added above. The following is the full function body for reference, but only the CORS line is new.

Note that the API isn’t currently using Authorization at all and won’t be for this post.

Client Application

Instead of redoing a lot of the same work that I covered in some of my posts on using Identity Server and Angular together I decided to copy the ClientApp directory and use it as a starting point. The rest of the client changes are going to assume the same starting point which means we will be using angular-auth-oidc-client instead of the Auth0 client to do the Open ID Connect bits.

Configuration values from appsettings.json

We need some setting from the ASP.NET Core part of the client application. First, add the following new settings to the  appsettings.json file.

Next,  Index.cshtml needs to be changed to provide some prerender data. The following shows the new data being passed into the Angular application (this post covers this in detail).

Now that the prerender values are being passed in we need to handle them in the  boot.server.ts file in the  createServerRenderer export. The following is the full list of values.

Down a bit in the file, the  setImmediate call needs to be changed to the following.

Next, in the  app.module.browser.ts file we need functions for getting the config values as well as the associated providers. The following is the full file without the imports.

Finally, in the  auth.service.ts file we need to inject the new configuration values. The following is the constructor that takes in the new values as well as uses them in the set up of the  OpenIDImplicitFlowConfiguration.

Make sure in the Auth0 client setup you allow the callback listed above or you will run into issues.

Wrapping Up

Working on this post further convinced me that Open ID Connect is the way to go. I basically took an implementation that was meant for Identity Server and used it with Auth0.

Make note that the reason the API is unsecured at this point is that I had an issue getting angular-auth-oidc-client to play nicely with Auth0 for some reason. I doubt it is an issue with either product just some sort of missing configuration on my part. This is the part of the post that I sunk so much time on. In the end, I decided to just skip it for now. If anyone does get that setup work I would love to see the sample so I know what I was doing wrong.

The completed code can be found here.

Identity Server: Upgrade Client to Angular 5

I have been working a lot on my basics sample project to explore some new client-side frameworks (React and Vue if you are interested). Since I have been away from the Identity Server sample for a while I thought it would be good to see what updates the project might need. It turns out that Angular was the big thing that was out of date. This post is going to cover the changes to get the project updated to Angular 5.

Package.json

In the Client App project open the  package.json file and update the version of the  @angular packages to at least the following version, and of course feel free to pin the exact version. I don’t just because of the nature of this sample.

At this point, I tried to run and got an error about the version of  rxjs being used. Instead of just blindly going package by package and seeing which versions were required I installed the Angular CLI and created a new Angular 5 application and used it as an example of what version I needed. Use the following commands if you would like to follow the same process since the current versions have changed by the time you are reading this post.

The above led me to the following version changes.

Attempt 2

At this point, I tried running the application again and received the following error.

Error: Version of @angular/compiler-cli needs to be 2.3.1 or greater. Current version is “5.0.1”.

As you can imagine I was surprised that 5.0.1 < 2.3.1. Turns out this is related to the version of @ngtools/webpack. This package deals with ahead-of-time compiling which my sample application uses, but the application I generated using the Angular CLI doesn’t. Updating to the following version cleared up the issue.

Open ID Connect Client

There was a much new version of the Open ID Connect Client that the Angular application is using so I upgrade it as well to the following version.

This version dropped the  startup_route so the following line had to be removed from the  AuthService class.

Final Steps

Now that the package versions are sorted run the following commands from a command prompt to make sure that all the new version are installed and in the proper places.

Wrapping Up

I am glad to have this upgrade done. It seems that every time I do one of these upgrades I end up down some rabbit hole. On the plus side, I seem to be getting faster at resolving the rabbit hole issues, or the frameworks have made a lot of progress on making sure the upgrade processes are simpler than they used to be. Either way, I get to expand my knowledge. I just need to schedule a bit more time before attempting upgrades.

The code in its finished state can be found here.

Vue: Contact Detail

Last week’s post covered adding a Vue project to the ASP.NET Core Basics example solution. This post is going to cover adding a read-only view of a contact’s detail to being the Vue sample a step closer to being in line with the Angular, Aurelia and React samples. The code before any changes can be found here.

Contact Class

The  Contact interface in the  contactlist.ts file should be deleted. Add a  contact.ts file to the  ClientApp/components/contacts/ directory. This will hold the replacement for the interface we just deleted. The full class definition follows.

This class is very simple and will be used later to show how a function call can be used as part of a view.

Contact Service

Since the application will now have two places that need to access the ASP.NET Core API lets to refactor the API access into a service. This is the same style used by the Aurelia, Angular and React applications. Add a  contactService.ts file to the  contacts directory. The service will provide functions to get all contacts or a single contact an ID. The following is the full class.

Now the API access in the  ContactListComponent can be refactored to use the service. First, add imports for contact and service.

Next, replace the fetch call with a service call.

Contact Detail Component

Add a  contactDetail.ts which will be the backing component for the contact detail view. The following is the full class. Pretty much all it is doing is using get contact service to get contact detail by ID when it is mounted.

Now add a  contactDetail.vue.html file for the UI bits of the contact detail. This is basically just HTML with the same binding syntax as before. Notice that the binding of address is a function call. The other Vue things to note are that the details will only show if contact is truthy using the v-if.

Routing with a Parameter

Finding the proper way to route with at parameter in Vue was not easy. The way it is done has evolved over time making find the right way a little challenging. The first step is to add a route for the contact detail by adding a new item to the  routes array in the  boot.ts file.

The  :id in the path denotes a parameter. The  props: true bit is also key to getting the ID when in the contact detail component. The  contactlist.vue.html needs to be updated to link to the contact detail route.

Finally, in the  ContactDetailComponent we need to use the ID. To do so we need an import to allow the use of the Prop decorator.

Now all that is needed is to apply the decorator to a property of the class that matches the name of the parameter in the route.

Now the ID can be used to get the proper contact from the contact service. The following is code that was already shown, but the full context of how the prop decorator is used is important so I am repeating it here.

Wrapping Up

This brings the projects one step closer to being on the same level feature-wise. Look for one more post to get the Vue project features lined up with the other samples in the solution.

Keep in mind that this is my first look at Vue and my examples may or may not be idiomatic.

The code in a finished state can be found here.

ASP.NET Core Basics: Vue with an API

In the past, I have done some exploration on AureliaAngular and React via the ASP.NET Core Basics series. This post is going to take a similar approach using Vue. The code for the project will be in the same repo as the previous basics examples and will be utilizing the same API to pull data. The code before adding the Vue project can be found here.

Project Creation

There is not a template for Vue built into Visual Studio, but there is a set of templates that can be used via the .NET CLI with the  dotnet new that includes Vue (as well as Aurelia and Knockout). A full list of available templates can be found here. The template we need is Microsoft.AspNetCore.SpaTemplates and can be installed using the following command from a command prompt.

Create a Vue folder at the same level as the other projects, for the samples this would be in the  src folder. In the command prompt navigate to the  src/Vue/ directory. Run the following command to create the Vue project.

After the project generation completes run the following to get the needed npm packages installed.

The last step is to get the new project added to the existing solution. Navigate the command prompt to your solution file. For the sample project, this is the root of the repo. Then run the following command (this could also be done through Visual Studio instead of using the CLI).

Adding the Contact List

In the  ClientApp/components directory add a new  contacts directory to house all the awesome contact related functionality we will be adding. Next, add a new  contactlist.ts. To this new file add the interface which defines what a Contact looks like.

Above the contact interface, add the following imports needed to create a Vue component.

Finally, add the contact list component. This component maintains a list of contacts which gets filled from our existing API when the component is mounted (see the docs for more information on Vue’s lifecycle hooks).

The following if the full component just to provide full context.

Next up is the UI for this contact list component. In the same directory add  contactlist.vue.html.  The following is the full file.

All of the above is pretty straightforward. All the Vue specific items have a  v- prefix.

Add the Contact List to Navigation

The last bit needed to have a working contact list is adding it to navigation so the user can get to the list. The routes are defined in the  boot.ts file in the  routes array. Add the following line to the array to handle our contact list.

Now that the router knows to handle the contact list it needs to be added to the navigation UI. Open the  /navmenu/navmenu.vue.html file and find the unordered list that is the navigation menu. Add a new list item to provide a link to the contact list.

Wrapping Up

Vue reminds me a lot of Aurelia in its simplicity so far which is awesome. Look for the same progression of posts for Vue that happened with React over the last few weeks.

The code in its final state can be found here.

React: Form for Contact Add

Last week’s post covered adding a read-only view of a contact’s details. As before the goal is to get the React project’s features in line with the Aurelia and Angular samples. This week we will be adding a form to all addition of a new contact. The code before any changes can be found here.

Contact List

On the contact list page, we need to add a link to create a contact. This will be added just after the header in the  ContactList.tsx file.

Routing

In order to stay in line with the other sample, the  ContactDetail component is going to be handling both the read-only view and the view to add a contact. This means the ID that is currently part of the contact detail needs to be optional. The following is the change to make ID optional by adding a question mark.

Contact Service

In the  ContactService class, we need to add a  save function. This new function will make a post request to the contacts API and return the new contact with the ID from the API to the caller.

Contact Detail

The  ContactDetail class is where most of the changes are. I had some trouble getting React’s forms to work directly with the instance of the contact class and ended up just storing the parts of a contact directly in state instead of as an object. I expect this is a failure on my part and not an issue with React. I may revisit this in the future. Below is the new structure of the state used by contact details.

Next, the  constructor needed to be changed to handle the new state structure and to handle being called without an ID.

Again, this is way more code than it would be the contact class were being used. Next, the render function needs to be adjusted to render the UI for the read-only view or the contact creation. The decision is based on the ID being set or undefined.

The render of an existing contact needs to be changed to use state instead of an instance of a contact.

The following is the render of the add contact UI. I will call out a couple of parts after. The bulk of the code is just rending of the form.

The following is the input for the contact’s name.

Since I decided to go with the controlled component route React will be responsible for being the source of truth, not the form its self. To accomplish this it is important that the input has a  name and an  onChange event handler set up. The following is the  handleChange function which uses the name from the on change event to update the proper property in the component’s state.

The following line is the reset button which will reset the state to blank out all the fields in the form.

<button className="btn btn-danger btn-lg" onClick={() => this.reset()}>Reset</button>

The  reset function just uses  setState to blank out all the fields.

Not surprisingly the submit button triggers a submit of the form. What happens on submit is defined in the opening form tag.

The  handleSubmit function takes the contact information in state and uses it to create a new instance of a  Contact which is then passed to the  ContactService to be saved. The service returns a new contact object from the server and the ID is stored to state.

If the server does return an ID for the new contact then the  redirect is set to true. Then will case the following code to run in  renderNewContact which will redirect the user back to the read-only view of the new contact.

Wrapping Up

This pretty much gets the React application in line with the Aurelia and Angular sample applications. It has been fun getting a handle on the very, very basics of React. While I am back in the basics sample projects I may go ahead and tackle a Vue sample next.

The finished code can be found here.