Okta Authentication Using Angularjs or JavaScript

This article will show you how to integrate Okta login capabilities into an AngularJS application. I couldn’t find any information on how to use angularjs 1.6 to develop an okta authentication app.

The okta stated that they did not support angularjs app, You need to use VanillaJS to add support with okta.

What is Okta?

Okta is a cloud service that allows developers to create, edit, and securely store user accounts and data, as well as connect them to one or more apps. You can use our API to do the following:

  • Authenticate and authorize your users
  • Store data about your users
  • Perform password-based and social login
  • Secure your application with multi-factor authentication

What’s Okta JavaScript SDK

Auth.js is a library wrapper for the Okta Authentication API. Use it when you need complete control of your sign in experience, or use the Okta Sign-In Widget for a pre-built, customizable experience

The Pre-Requisites:

Create Angularjs applicationApp

Let’s create an angular js application, I have created a hello-ang/ app folder into the workspace.

cd > hello-ang/

Created an index.html file into the root of the folder, This file will include all CSS and js files. I also added the CDN file path of the okta auth SDK file.

<!DOCTYPE html>
<html class="no-js"> <!--<![endif]-->
<head>
    <base href="/">
    <!-- Meta-Information -->
    <title>Test ng app</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="description" content="phpflow.com">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Vendor: Bootstrap Stylesheets http://getbootstrap.com -->
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- Our Website CSS Styles -->
    <link rel="stylesheet" href="/css/main.css">
    <script src="https://global.oktacdn.com/okta-auth-js/5.2.3/okta-auth-js.polyfill.js" type="text/javascript"></script>
	<script src="https://global.oktacdn.com/okta-auth-js/5.2.3/okta-auth-js.min.js" type="text/javascript"></script>
    
</head>
<body ng-app="tutorialWebApp">
<div ng-include='"/templates/header.html"'></div>
<div ng-view></div>
<div ng-include='"/templates/footer.html"'></div>

<!-- Vendor: Javascripts -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>

<!-- Vendor: Angular, followed by our custom Javascripts -->
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular-route.min.js"></script>

<!-- Our Website Javascripts -->
<script src="/js/main.js"></script>

</body>
</html>

Create a main.js file and paste the below code into his folder:

/**
 * Main AngularJS Web Application
 */
var app = angular.module('phpflowApp', [
  'ngRoute'
]);

/**
 * Configure the Routes
 */
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
  $routeProvider
    // Home
    .when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"})
    // else 404
    .otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
	  $locationProvider.html5Mode(true);
}]);

/**
 * Controls Pages
 */
app.controller('PageCtrl', function ( $scope) {
  var config = {
    // Required config
    issuer: 'https://xxxx/oauth2/default',
    // Required for login flow using getWithRedirect()
    clientId: 'xxxx',
    redirectUri: 'http://localhost:8080/',
    responseType: 'code',
    devMode: true
  };
  $scope.username = '';
  var authClient = new OktaAuth(config);
  authClient.start();

  let signin = async function() {
    if (authClient.isLoginRedirect()) {
      try {
        await authClient.handleLoginRedirect();
      } catch (e) {
        // log or display error details
        console.log('Exception - '+e);
      }
    } else if (!await authClient.isAuthenticated()) {
      // Start the browser based oidc flow, then parse tokens from the redirect callback url
      console.log('signInWithRedirect - ');
      authClient.signInWithRedirect();
    } else {
      // User is authenticated
      console.log('authenticated - ');
      Promise.all([
        authClient.tokenManager.get('idToken')
      ])
      .then(([idTokenObject]) => {
        localStorage.setItem("username", idTokenObject['claims']['name']);
        $scope.username = localStorage.getItem("username");
        console.log($scope.username);
        //return authClient.token.getUserInfo(accessTokenObject, idTokenObject);
      });
    }
  }
  signin();
  console.log($scope.username);
  $scope.logout = function() {
    console.log('hellooo');
    authClient.signOut();
  }
});

install http-server package here for developement server:
$hello-ang> npm install -g http-server

Let’s create a partials/home.html file:

<div id="myCarousel" class="carousel slide">

<div class="section">

    <div class="container">

           <div class="row" ng-if="username == ''">
                <h2>Hey, You need to sign-in</h2>
                <a class="btn btn-primary" href="/">Login</a>

            </div>

            <div class="row" ng-if="username != ''">
                <h2 class="page-header">Welcome User:<small style="background-color: yellow;">{{username}}</small></h2>
                <a class="btn btn-primary" ng-click="logout()">Logout</a>
                
            </div>

        </div>
<!-- /.container -->

Create and Configure a New Okta applicationApp

Let’s Create a app into developer console. I assumed, You have developer account and logged in.

Navigate to Applications in the sidebar navbar and then click Create Application button.

okta-create-app

Now select OpenID and SPA as the platform and click Next.

options-okta

Enter app_name, sign-in and sign-out redirect UI.

general-setting

Finally, ensure that Login redirect URIs contains http://localhost:8080 and click Done.

User Authentication Using Okta

Let’s walk you through adding user authentication to your angularjs or JavaScript application.

Get Okta App Details

Open app details page from okta developer dashboard, Copy okta client-id and okta domain name from here:

okta-details-app

Configure Angularjs app

We will paste above details into main.js file:

var config = {
    // Required config
    issuer: 'https://oktadomain/oauth2/default',
    // Required for login flow using getWithRedirect()
    clientId: 'client-id',
    redirectUri: 'http://localhost:8080/',
    responseType: 'code',
    devMode: true
  };

Replace oktadomain and client-id with your app details.

Start app

$hello-ang>http-server -o

Your HTTP server should startup. Open a browser and navigate to http://localhost:8080.

You will get the below page:

okta-user-sign-in

Leave a Reply

Your email address will not be published. Required fields are marked *