DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • The Technology Stack Needed To Build a Web3 Application
  • How to Build a Full-Stack App With Next.js, Prisma, Postgres, and Fastify
  • Apache Aries: Helping Enterprise Developers Build OSGi Apps
  • 5 Simple Tips to Keep Dockerized Apps Secure

Trending

  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • How To Develop a Truly Performant Mobile Application in 2025: A Case for Android
  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  1. DZone
  2. Coding
  3. Frameworks
  4. Build an Angular App With User Management in 15 Mins

Build an Angular App With User Management in 15 Mins

Follow this guide to create a quick, easy Angular app with authentication provided by Okta.

By 
Matt Raible user avatar
Matt Raible
·
Mar. 19, 18 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
23.2K Views

Join the DZone community and get the full member experience.

Join For Free

Angular is holding strong as the third most popular UI framework, behind React and HTML5. In this article, I’ll show you a quick way to get started with Angular, and add user management with Okta’s Sign-In Widget. If you’re just getting started with Angular, you might want to read my Angular tutorial. If you’d like to get the source code used in this article, you can find it on GitHub.

Why User Authentication With Okta?

Okta provides an API service that allows developers to create, edit, and securely store user accounts and user account data, and connect them with one or multiple applications. We make user account management easier, more secure, and scalable so you can get to production sooner.

The Okta Sign-in Widget provides an embeddable JavaScript sign-in implementation that can be easily customized. The Sign-in Widget carries the same feature set in the standard Okta sign-in page of every tenant – with the added flexibility to change the look-and-feel. Included in the widget is support for password reset, forgotten password, and strong authentication – all of which are driven by policies configured in Okta. Developers don’t have to write a single line of code to trigger these functions from within the widget. For consumer-facing sites, social providers are also supported in the widget.

Create an Angular Application

Angular 4 was recently released, as well as Angular CLI 1.4.4. To see how you might use Okta’s Sign-In Widget in a simple Angular application, create a new application with Angular CLI. First, you’ll need to install Angular CLI.

NOTE: This post has been updated to use Angular 5 and Angular CLI 1.5.5.

npm install -g @angular/cli


After this command completes, you can create a new application.

[mraible:~] $ ng new angular-okta-example
  create angular-okta-example/README.md (1034 bytes)
  create angular-okta-example/.angular-cli.json (1255 bytes)
  create angular-okta-example/.editorconfig (245 bytes)
  create angular-okta-example/.gitignore (516 bytes)
  create angular-okta-example/src/assets/.gitkeep (0 bytes)
  create angular-okta-example/src/environments/environment.prod.ts (51 bytes)
  create angular-okta-example/src/environments/environment.ts (387 bytes)
  create angular-okta-example/src/favicon.ico (5430 bytes)
  create angular-okta-example/src/index.html (305 bytes)
  create angular-okta-example/src/main.ts (370 bytes)
  create angular-okta-example/src/polyfills.ts (2405 bytes)
  create angular-okta-example/src/styles.css (80 bytes)
  create angular-okta-example/src/test.ts (1085 bytes)
  create angular-okta-example/src/tsconfig.app.json (211 bytes)
  create angular-okta-example/src/tsconfig.spec.json (304 bytes)
  create angular-okta-example/src/typings.d.ts (104 bytes)
  create angular-okta-example/e2e/app.e2e-spec.ts (302 bytes)
  create angular-okta-example/e2e/app.po.ts (208 bytes)
  create angular-okta-example/e2e/tsconfig.e2e.json (235 bytes)
  create angular-okta-example/karma.conf.js (923 bytes)
  create angular-okta-example/package.json (1325 bytes)
  create angular-okta-example/protractor.conf.js (722 bytes)
  create angular-okta-example/tsconfig.json (363 bytes)
  create angular-okta-example/tslint.json (3097 bytes)
  create angular-okta-example/src/app/app.module.ts (316 bytes)
  create angular-okta-example/src/app/app.component.css (0 bytes)
  create angular-okta-example/src/app/app.component.html (1141 bytes)
  create angular-okta-example/src/app/app.component.spec.ts (986 bytes)
  create angular-okta-example/src/app/app.component.ts (207 bytes)
You can `ng set --global packageManager=yarn`.
Installing packages for tooling via npm.
Installed packages for tooling via npm.
Successfully initialized git.
Project 'angular-okta-example' successfully created.
[mraible:~] 42s $


This will create a new angular-okta-example directory and install all the necessary dependencies. To verify everything works, run ng e2e in a terminal window. All tests should pass and you should see results like the following.

Running e2e

Integrate Okta’s Sign-In Widget in Angular

Now we’re going to leverage Okta’s Sign-In Widget for an easily customizable login view. To start, install the Okta Sign-In Widget using npm.

npm install --save @okta/okta-signin-widget


Add the widget’s CSS to src/styles.css:

@import '~@okta/okta-signin-widget/dist/css/okta-sign-in.min.css';
@import '~@okta/okta-signin-widget/dist/css/okta-theme.css';


Create src/app/shared/okta/okta.service.ts and use it to wrap the widget’s configuration and make it an injectable service.

import { Injectable } from '@angular/core';
import * as OktaSignIn from '@okta/okta-signin-widget';

@Injectable()
export class Okta {
  widget;

  constructor() {
    this.widget = new OktaSignIn({
      baseUrl: 'https://{yourOktaDomain}.com',
      clientId: '{clientId}',
      redirectUri: 'http://localhost:4200',
      authParams: {
        issuer: 'default'
      }
    });
  }

  getWidget() {
    return this.widget;
  }
}


To make this service available to all components in the application, modify app.module.ts and list Okta as a provider.

import { Okta } from './shared/okta/okta.service';

@NgModule({
  ...
  providers: [Okta],
  bootstrap: [AppComponent]
})


Before this will work, you’ll need to create an OpenID Connect (OIDC) application in Okta so you can replace the {yourOktaDomain} and {clientId} references when initializing the widget.

Create an OpenID Connect App in Okta

OpenID Connect is built on top of the OAuth 2.0 protocol. It allows clients to verify the identity of the user and, as well as to obtain their basic profile information. To learn more, see http://openid.net/connect.

Login to your Okta account, or create one if you don’t have one. Navigate to Applications and click on the Add Application button. Select SPA and click Next. On the next page, specify http://localhost:4200 as a Base URI, Login redirect URI, and Logout redirect URI. Click Done and you should see settings like the following.

OIDC App Settings

Show the Sign-In Widget

After making these changes, copy the your Client ID and Platform ID into okta.service.ts. Then modify app.component.ts to use the Okta service and the widget to login/logout.

import { Component, ChangeDetectorRef, OnInit } from '@angular/core';
import { Okta } from './shared/okta/okta.service';

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

  constructor(private okta: Okta, private changeDetectorRef: ChangeDetectorRef) {
    this.oktaSignIn = okta.getWidget();
  }

  showLogin() {
    this.oktaSignIn.renderEl({el: '#okta-login-container'}, (response) => {
      if (response.status === 'SUCCESS') {
        this.user = response.claims.email;
        this.oktaSignIn.remove();
        this.changeDetectorRef.detectChanges();
      }
    });
  }

  ngOnInit() {
    this.oktaSignIn.session.get((response) => {
      if (response.status !== 'INACTIVE') {
        this.user = response.login;
        this.changeDetectorRef.detectChanges();
      } else {
        this.showLogin();
      }
    });
  }

  logout() {
    this.oktaSignIn.signOut(() => {
      this.user = undefined;
      this.changeDetectorRef.detectChanges();
      this.showLogin();
    });
  }
}


NOTE: Using Angular’s ChangeDetectorRef is necessary to manually trigger the change detector and let the view know that variables have changed. See okta/okta-signin-widget#268 for more information.

And modify app.component.html to have a <div> with id="okta-login-container" and a place to show the logged in user’s email.

<div *ngIf="!user" id="okta-login-container"></div>

<div *ngIf="user">
  Hello {{user}}

  <button (click)="logout()">Logout</button>
</div>


Run ng serve, and open your browser to http://localhost:4200. You should see the sign-in widget. Enter one of your user’s credentials to login. You should see a “Hello {email}” message with a logout button.

Login Success

If it works - congrats! If it doesn’t, please post a question to Stack Overflow with an okta tag, or hit me up on Twitter.

Customize the Widget CSS

If you’d like to customize the widget’s CSS, the easiest way is you write your own CSS. Remove the CSS @import statements you added to src/styles.css and install Bootstrap 4.

npm install bootstrap@4.0.0-beta.2 --save


NOTE: If you’re using Yarn (instead of npm), you might experience this issue. If you do, the workaround is to modify your package.json and change the Bootstrap version from "^4.0.0-beta.2" to "4.0.0-beta.2".

Add an @import for Bootstrap 4 and a few style rules to position elements. Copy the following code into src/styles.css.

@import "~bootstrap/dist/css/bootstrap.css";

#okta-login-container {
  margin: 0 auto;
  max-width: 400px;
  border: 1px solid silver;
  padding: 20px;
  box-shadow: 5px 5px 5px 0 silver;
}

#okta-login-container input {
  margin-bottom: 5px;
  width: 100%;
  padding: 5px;
}

#okta-login-container input[type=checkbox] {
  width: 25px;
}


After making these changes, the sign-in widget will look like the following screenshot.

Custom CSS

Fix Your Tests

If you try to run npm test or ng test, tests will fail:

Chrome 62.0.3202 (Mac OS X 10.12.6): Executed 3 of 3 (3 FAILED) (0 secs / 0.157 secs)
Chrome 62.0.3202 (Mac OS X 10.12.6) AppComponent should render title in a h1 tag FAILED
Failed: No provider for Okta!


To fix this, specify Okta as a provider in src/app/app.component.spec.ts.

import { Okta } from './shared/okta/okta.service';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      providers: [Okta]
    }).compileComponents();
  }));


After making this changes, you should see the sweet smell of success.

Chrome 62.0.3202 (Mac OS X 10.12.6): Executed 3 of 3 SUCCESS (0.77 secs / 0.759 secs)


Protractor tests should still work as well. You can prove this by running ng e2e in a terminal window.

Angular + Okta

You can find a completed version of the application created in this blog post on GitHub. In a future post, I’ll show you how to create a more Angular-native experience, where you control the HTML for the login form.

Building authentication in an application is hard. It’s even less fun to build it over and over again in each application you build. Okta does the hard part for you and makes it a lot more fun to be a developer! Sign up for a forever-free developer account and try Okta today!.

I hope you’ve enjoyed this quick tour of our Angular support. If you have questions about Okta’s features, or what we’re building next, please hit me up on Twitter, post a question to Stack Overflow with an “okta” tag, or open a new issue on GitHub.

Build an Angular App with Okta's Sign-in Widget in 15 Minutes was originally published on the Okta developer blog on March 27, 2017.

AngularJS app application Build (game engine)

Published at DZone with permission of Matt Raible, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Technology Stack Needed To Build a Web3 Application
  • How to Build a Full-Stack App With Next.js, Prisma, Postgres, and Fastify
  • Apache Aries: Helping Enterprise Developers Build OSGi Apps
  • 5 Simple Tips to Keep Dockerized Apps Secure

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: