angular spa, asp.net core and authentication – Part 2, Authenticating with MVC

In Part 1, I discussed my rationale for the following set-up using asp.net core MVC for authentication for an  angular single page application (SPA) frontend and an asp.net core backend.  In this post, I’m going to build on concepts from Michel Dymel’s two project set-up, as well as parts of the MS Javascriptservices SPA template project.  I am setting this up on Windows, so I’ll be using Visual Studio 2017 Community Edition for backend editing, and VS Code for frontend.

Step 1: Asp.Net Core Backend/Server Project

  1. Within Visual Studio 2017, Create a new asp.net core project, inside a new solution
  2. Choose to create an MVC/API application with User Authentication (along with Git)
  3. If adding this to another git repo, then add a .gitignore file manually for VS project
  4. The backend project should remain the default project (bold in solution explorer)
  5. In project properties, under debug tab, note the App URL (http://localhost:port)
    1. The app url is used below in setting the proxy

newMvcApp2017-1

 newMvcApp2017-2

Step 2: Angular-Cli Frontend project

  1. Add a new netCore class library project inside the solution created above
    1. Delete the default class1.cs that is automatically created
  2. Open a powershell window here within this new project directory
  3. Prepare to use node/npm/angular-cli
    1. Install or update node (check version with “node -v”)
    2. Update angular-cli
      1. npm uninstall -g @angular/cli
      2. npm cache clean
      3. npm install -g @angular/cli@latest
  4. Create a new angular project via the command-line interface (CLI)
    1. ng new [projectname] –routing –style scss –prefix [myPrefix]
      1. choose your own projectname (e.g. frontend) and prefix (for components, directives)
      2. for style, select scss or less (css is the default)
      3. If  routing flag is specified, angular will automate routing set-up
    2.  Set a proxy configuration pointing to the asp.net core backend as above
      1. This uses Michal Dymel’s set-up 
      2. This will only be used for development (npm start)
      3. Create a “proxy.conf.json” file in the main frontend directory:
      4. {
          "/api": {
            "target": "http://localhost:61234",
            "secure": false
          }
        }
      5. Edit the start command in “package.json”
        1.   “start”: “ng serve –proxy-config proxy.conf.json”
        2. To use the proxy, run “npm start”, NOT “ng serve”
    3. Set up the production build pipeline for the angular app
      1. On “ng Build”, the angular app distribution is written to wwwroot
      2. In the angular-cli.json file, edit “OutDir”
      3.  “outDir”: “../backend/wwwroot/angular_dist/”
        1. Writing to wwwroot will clear the directory (angular-cli wipes it)
        2. Therefore, better to write to a subdir

Step 3: Other Angular Frontend Customizations

Now, for a compromise.  I want a fast set-up for the server login without much customization.   I typically use Bootstrap with angular, but instead of using jquery, I use ng-bootstrap, and I’ve started using Bootstrap 4, which is still in alpha version as I write this blog entry.

However,  Asp.net uses Bootstrap 3 and JQuery as its default, so I’m going to compromise and use this set-up for my app (Bootstrap 3, jquery).  I will be using the Sass version of Bootstrap.  Finally, the bootstrap css, and script libraries (jquery, bootstrap) should only be loaded once (client or server).  I need to load them either in the angular-cli.json or in the server _layout.cshtml.  Since I will frequently run the angular app in memory, outside of the asp.net app, I will want the scripts to be loaded via the angular-cli.json.  I’ll need to therefore make sure that the layout.cshtml used to hold the angular app does not load these scripts also.

Adding Boostrap V3

  1. npm install –save bootstrap-sass font-awesome jquery
  2. npm install @types/jquery –save-dev
  3. create empty file in “src/: _variables.scss” and add the following:
$icon-font-path: '../node_modules/bootstrap-sass/assets/fonts/bootstrap/';
$fa-font-path:'../node_modules/font-awesome/fonts';
  1. add to styles.scss file:
@import 'variables';
@import '../node_modules/bootstrap-sass/assets/stylesheets/_bootstrap';
@import '../node_modules/font-awesome/scss/font-awesome';

Finally set styles and scripts objects in  the “angular-cli.json file:”

"styles": ["styles.scss"],
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
 "../node_modules/bootstrap-sass/assets/javascripts/bootstrap.min.js"
],

Step 4: AspNet MVC Index View to show the angular Spa

Change the “Backend\Views\Home\Index.cshtml” to contain the following code:

@{
 ViewData["Title"] = "Angular App";
 Layout = "_Layout_ngEmbed";
}

Loading...

@section scripts {
http://~/angular_dist/inline.bundle.js
http://~/angular_dist/polyfills.bundle.js
http://~/angular_dist/styles.bundle.js
http://~/angular_dist/vendor.bundle.js
http://~/angular_dist/main.bundle.js
}

Notice that the Layout is being set to a new file “Layout_ngEmbed.cshtml ” (instead of using the default _Layout.cshtml).  We need to customize a couple of items in the Layout file, specific for pages that have an embedded angular app:

  1. In the shared folder, copy “_Layout.cshtml” to a new file and name it “_Layout_ngEmbed.cshtml”
  2. Delete script files that will instead be loaded by the angular app
    1. Delete all links to the bootstrap.css
    2. Delete all script tags to bootstrap.js and jquery.js
  3. In the head section, add a base href tag (angular will need this):

Now, to show the frontend angular code embedded inside the backend MVC app:

  1. at the powershell prompt, type “ng build”
  2. In Visual Studio, in the backend app, “Ctrl F5” (run without debug)

To run the angular app alone, in memory, but still access the api:

  1. at the powershell prompt, “npm serve” (this will run “ng serve” with proxy)
  2. Note that the backend needs to be running (Ctrl-F5) for Api to work

Next Steps

That is it for a basic set-up.  The angular app can be run on its own to allow for rapid development and can still call the Api even when not embedded.  When embedded in the MVC app, login is possible and that single asp.net core MVC project (backend) can be deployed to a server.

Some additional to-do items:

  1. Login and call protected Apis either with tokens or cookies
  2. Login and authorize api access via claims or roles
  3. apply user information to app content (e.g. username as author)
  4. Build backend admin pages in MVC
  5. Automate frontend “ng build” as part of backend pre-build of the project
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.