Translate

Thursday 10 January 2019

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 !</h1>

<div *ngIf="givenName">
  <h2>Hi, !</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.

The post Build an App with Everything New & Noteworthy in Angular 7 appeared first on SitePoint.



No comments:

Post a Comment