JavaScript
Matt Raible, Jan 10

Build an App with Everything New & Noteworthy in Angular 7

Angular 7 was released earlier this quarter and I’m pumped about a few of its features. If you’ve been following Angular since Angular 2, you know that upgrading can sometimes be a pain. There was no Angular 3, but upgrading to Angular 4 wasn’t too bad, aside from a bunch of changes in Angular’s testing infrastructure. Angular 4 to Angular 5 was painless, and 5 to 6 only required changes to classes that used RxJS.

Before I dive into showing you how to build an Angular app with authn/authz, let’s take a look at what’s new and noteworthy in this release.

Upgrade to Angular 7

If you created your app with Angular CLI, chances are you can easily upgrade to the latest release using ng update.

ng update @angular/cli @angular/core

You can also use the Angular Update Guide for complete step-by-step instructions.

Angular Update Guide

What’s New in Angular 7

There are a few notable features in Angular 7, summarized below:

  • CLI prompts: this feature has been added to Schematics so you can prompt the user to make choices when running ng commands.
  • Performance enhancements: the Angular team found many people were using reflect-metadata as a dependency (rather than a dev-only dependency). If you update using the aforementioned methods, this dependency will automatically be moved. Angular 7 also adds bundle budgets so you’ll get warnings when your bundles exceed a particular size.
  • Angular Material: Material Design had significant updates in 2018 and Angular Material v7 reflects those updates.
  • Virtual Scrolling: this feature allows you to load/unload parts of a list based on visibility.
  • Drag and Drop: this feature has been added to the CDK of Angular Material.

Bundle budgets is the feature that excites me the most. I see a lot of Angular apps with large bundle sizes. You want your baseline cost to be minimal, so this feature should help. The following defaults are specified in angular.json when you create a new project with Angular CLI.

"budgets": [{
  "type": "initial",
  "maximumWarning": "2mb",
  "maximumError": "5mb"
}]

You can use Chrome’s data saver extension for maximum awareness of the data your app uses.

For more details on what’s new in Angular 7, see the Angular blog, coverage on InfoQ, or the Angular project’s changelog.

Now that you know how awesome Angular 7 is, let’s take a look at how to create secure applications with it!

Create a Secure Angular 7 Application

An easy way to create Angular 7 apps is using the Angular CLI. To install it, run the following command:

npm i -g @angular/cli

The example below uses Angular CLI 7.1.0. To verify you’re using the same version, you can run ng --version.

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 7.1.0
Node: 11.1.0
OS: darwin x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.11.0
@angular-devkit/core         7.1.0
@angular-devkit/schematics   7.1.0
@schematics/angular          7.1.0
@schematics/update           0.11.0
rxjs                         6.3.3
typescript                   3.1.6

To create a new app, run ng new ng-secure. When prompted for routing, type "Y". The stylesheet format is not relevant to this example, so choose whatever you like. I used CSS.

After Angular CLI finishes creating your app, cd into its directory, run ng new, and navigate to [http://localhost:4200](http://localhost:4200) to see what it looks like.

Default Angular App!

Add Identity and Authentication to Your Angular 7 App with OIDC

If you’re developing apps for a large enterprise, you probably want to code them to use the same set of users. If you’re creating new user stores for each of your apps, stop it! There’s an easier way. You can use OpenID Connect (OIDC) to add authentication to your apps and allow them all to use the same user store.

OIDC requires an identity provider (or IdP). There are many well-known IdPs like Google, Twitter, and Facebook, but those services don’t allow you to manage your users like you would in Active Directory. Okta allows this, and you can use Okta’s API for OIDC.

Register for a forever-free developer account, and when you’re done, come on back so you can learn more about how to secure your Angular app!

Free developer account!

Now that you have a developer account, I’ll show you several techniques for adding OIDC authentication to you Angular 7 app. But first, you’ll need to create a new OIDC app in Okta.

Create an OIDC App in Okta

Log in to your Okta Developer account and navigate to Applications > Add Application. Click Web and click Next. Give the app a name you’ll remember, and specify [http://localhost:4200](http://localhost:4200) as a Login redirect URI. Click Done. Edit your app after creating it and specify [http://localhost:4200](http://localhost:4200) as a Logout redirect URI too. The result should look something like the screenshot below.

Okta OIDC App

Use angular-oauth2-oidc

The angular-oauth2-oidc library provides support for OAuth 2.0 and OIDC. It was originally created by Manfred Steyer and includes many community contributions.

Install angular-oauth2-oidc using the following command:

npm i angular-oauth2-oidc@5.0.2

Open src/app/app.module.ts and import OAuthModule as well as HttpClientModule.

import { HttpClientModule } from '@angular/common/http';
import { OAuthModule } from 'angular-oauth2-oidc';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    OAuthModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Modify src/app/app.component.ts to import OAuthService and configure it to use your Okta application settings. Add login() and logout() methods, as well as a getter for the user’s name.

import { Component } from '@angular/core';
import { OAuthService, JwksValidationHandler, AuthConfig } from 'angular-oauth2-oidc';

export const authConfig: AuthConfig = {
  issuer: 'https://{yourOktaDomain}/oauth2/default',
  redirectUri: window.location.origin,
  clientId: '{yourClientId}'
};

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ng-secure';

  constructor(private oauthService: OAuthService) {
    this.oauthService.configure(authConfig);
    this.oauthService.tokenValidationHandler = new JwksValidationHandler();
    this.oauthService.loadDiscoveryDocumentAndTryLogin();
  }

  login() {
    this.oauthService.initImplicitFlow();
  }

  logout() {
    this.oauthService.logOut();
  }

  get givenName() {
    const claims = this.oauthService.getIdentityClaims();
    if (!claims) {
      return null;
    }
    return claims['name'];
  }
}

Modify src/app/app.component.html to add Login and Logout buttons.

<h1>Welcome to {{ title }}!</h1>

<div *ngIf="givenName">
  <h2>Hi, {{givenName}}!</h2>
  <button (click)="logout()">Logout</button>
</div>

<div *ngIf="!givenName">
  <button (click)="login()">Login</button>
</div>

<router-outlet></router-outlet>

Restart your app and you should see a login button.

App with Login button

Click the login button, sign in to your Okta account, and you should see your name with a logout button.

App with name and Logout button

Pretty slick, eh?

Okta’s Angular SDK

You can also use Okta’s Angular SDK to implement the same functionality. You can start by installing it.

WordPress
SitePoint Team, Jan 08

How to Choose a WordPress Theme in 2019: A Selection of the Best

Want to know how to choose a WordPress theme? We've selected what we consider to be the best 15 for 2019 for your review.
WordPress
SitePoint Team, Dec 19

Visual Composer: The Brain-Twisting Story of the Name Change

If you have been a Visual Composer user for some time, you have witnessed some changes happening that might have been a little bit confusing.
Web
SitePoint Team, Dec 11

Why More Web Designers Should Give Pre-built Websites a Try

There's a heated and seemingly never-ending debate in the web design industry about whether web designers should always start their design work from scratch or not.
30 COMMENTs
JavaScript
Craig Buckler, Dec 06

Best JavaScript Frameworks, Libraries and Tools to Use in 2019

Craig Buckler comes up with his list of the top JavaScript frameworks, libraries and tools, and explains when to use them.
JavaScript
David Neal, Dec 06

How to Use TypeScript to Build a Node API with Express

The goal of this tutorial is to show you how to build a new Node.js application using TypeScript and Express.
Web
David Cramer, Dec 05

How to Debug Python Errors

One of Sentry’s powerful features comes with languages like Python. In Python, PHP, and the JVM, we’re able to introspect more deeply into the runtime and give you additional data.
JavaScript
Braden Kelley, Dec 04

How to Create and Verify JWTs with Node

In this tutorial, I’ll show you how a modern and secure authentication approach. By the end, you’ll be able to create and verify JWTs yourself in Node.
JavaScript
Holger Schmitz, Nov 29

Build a Basic CRUD App with Angular and Node

In this tutorial, you will be developing a simple Angular single page app with a REST backend, based on Node and Express.
Web
SitePoint Team, Nov 26

Cyber Monday: Elegant Themes Offers 25% OFF in Biggest Discount Ever

Little gems hidden in an array of Cyber Monday details are easy to miss.
1 COMMENT
JavaScript
James Hibbard, Nov 26

jQuery setTimeout() Function Examples

James Hibbard explains how the jQuery and JavaScript function setTimeout() works, and gives examples and links to further reading.
15 COMMENTs
JavaScript
Olayinka Omole, Nov 23

Quick Tip: How to Sort an Array of Objects in JavaScript

Olayinka Omole shows you how to dynamically sort an array of objects in JavaScript, using Array.prototype.sort() and a custom compare function.
Web
Craig Buckler, Nov 22

Getting Started with Sentry.io Error Tracking

Writing code can be fun. Testing is another matter. Errors can still slip into the best production code. How can you detect those issues?
WordPress
Tonino Jankov, Nov 21

How to Build a WordPress Theme from Scratch: Final Steps

In this article, Tonino completes his foray into building a WordPress theme from scratch, focusing on refining templates, adding meta information, post thumbnails, sidebars, user-friendly controls and more.
9 COMMENTs
JavaScript
Yaphi Berhanu, Nov 20

Quick Tip: Get URL Parameters with JavaScript

Yaphi Berhanu shows how to parse the query string and retrieve URL parameters using only vanilla JavaScript. 
Web
John Fairhurst, Nov 20

Jumpstart Your Business by Being Smart

Ben Strickland explains how to be smart when starting a business, discussing how much time to invest, how to avoid failure with research, and how to know your customer by interviewing, talking with them, and building relationships with them.
WordPress
Tonino Jankov, Nov 19

How to Build a WordPress Theme from Scratch: the Basics

This second part on creating a WordPress theme from scratch shows how to create a very basic WordPress theme, add in Bootstrap styles and scripts, separate header and footer output into their respective partials, and leverage the crucial functions.php file.
Web
Angela Phung, Nov 16

Get to Know the Winners of the Alibaba Cloud Competition

As you may have seen, we’ve recently partnered with Alibaba Cloud to find the best tips and tutorials for making the most out of Alibaba Cloud Services.
12 COMMENTs
Design & UX
Daniel Schwarz, Nov 13

Fonts and Colors Used by Facebook, Twitter, Instagram, Google + More

A cheatsheet of the fonts and colors used by Facebook, Twitter, Instagram, Pinterest, Messenger, Snapchat, and YouTube, with links to official brand assets.
WordPress
Tom Ewer, Nov 13

Developing a WordPress REST API App: Getting Started

This introductory article is part one in a tutorial series taking non-technical users through the building of a WordPress REST API app using React.
WordPress
Tonino Jankov, Nov 13

How to Build a WordPress Theme from Scratch: First Steps

Tonino introduces WordPress themes, showing how they work, how they’re structured, the PHP architecture behind them, and other relevant information, as the first step in learning how to build a WordPress theme from scratch.
Web
Martin Tumusiime, Nov 12

How to Deploy and Host a Joomla Website on Alibaba Cloud ECS

This guide will walk you through setting up and deploying a Joomla! website on an Alibaba Cloud Elastic Compute Service (ECS) instance with Ubuntu 16.04.
2 COMMENTs
Web
Maria Antonietta Perna, Nov 11

Five Techniques to Lazy Load Images for Website Performance

Maria Antonietta Perna highlights the benefits of lazy loading images on websites and shows five approaches to implement lazy loading for your website.
Web
Natalie Harris-Briggs, Nov 09

6 Ways to Bring Your Development Team Together with Technology

Are you looking for better ways of bringing the team together? Would you benefit from an arsenal of tools that facilitate team working?