Install Angular CLI:
npm install -g @angular/cli
Create a new project using Angular CLI:
ng new okta-demo
Install the Okta SignIn Widget:
npm install @okta/okta-signin-widget --save
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';
Add the widget's JS to .angular-cli.json
:
"scripts": [
"../node_modules/@okta/okta-signin-widget/dist/js/okta-sign-in.min.js"
],
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';
declare let OktaSignIn: any;
@Injectable()
export class Okta {
widget;
constructor() {
this.widget = new OktaSignIn({
baseUrl: 'https://dev-158606.oktapreview.com',
clientId: 'RLroj4NiQtyPWWthGUnN',
redirectUri: 'http://localhost:4200',
authParams: {
responseType: ['id_token', 'token']
}
});
}
getWidget() {
return this.widget;
}
}
Import this widget into any Angular component or service and use constructor injection. For example:
oktaSignIn;
constructor(private okta: Okta) {
this.oktaSignIn = okta.getWidget();
}
To show the widget app.component.html
, add the following HTML:
<div *ngIf="!user" id="okta-login-container"></div>
<div *ngIf="user">
Hello {{user}}
<button (click)="logout()">Logout</button>
</div>
Then modify app.component.ts
to use the Okta
service and the widget to login/logout:
import { Component, 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 works!';
user;
oktaSignIn;
constructor(private okta: Okta) {
this.oktaSignIn = okta.getWidget();
}
showLogin() {
this.oktaSignIn.renderEl({el: '#okta-login-container'}, (response) => {
console.log('response', response);
if (response.status === 'SUCCESS') {
this.oktaSignIn.tokenManager.add('authToken', response[1]);
this.user = response[0].claims.email;
}
});
}
ngOnInit() {
this.oktaSignIn.session.get((response) => {
if (response.status !== 'INACTIVE') {
this.user = response.login
} else {
this.showLogin();
}
});
}
logout() {
this.oktaSignIn.signOut(() => {
this.showLogin();
this.user = null;
});
}
}