This is the second part in two part series that will walk you step by step how to integrate Okta OIDC authentication for Single Page Applications. This 2 part series will cover:
- Part 1: Create a OIDC SPA Application in Okta
- Part 2: Integrate the Okta application with any SPA that runs on Javascript, Angular, React, Vue
By the end of this tutorial you will be able to successfully setup Okta OIDC authentication
Install the okta npm module
npm install --save @okta/okta-auth-js
Create a service file which has the definition of all the sign in and sign out methods. Create a global instance of OktaAuth object.
const oktaAuth = new OktaAuth({
clientId: <CLIENT_ID>,
issuer: <ISSUER>,
redirectUri: http://localhost:8080/callback,
pkce: false,
tokenManager: {
autoRenew: false
}
});
Implement the login method which will use the getWithRedirect method for silent authentication.
login() {
// Launches the login redirect.
this.oktaAuth.token.getWithRedirect({
scopes: ['openid']
})
}
The url will get redirected to Okta to get authenticated and after successful authentication the url will be redirected to the callback component mentioned in the login redirect uri field.
Implement the handleAuthentication method in the callback component as follows
export class CallbackComponent {
constructor(private okta: OktaauthService, private router: Router) {
okta.handleAuthentication().then(data => {
let referPath = localStorage.getItem('appReffererPath')!
let navigateUrl = decodeURI(referPath)
const navigationExtras: NavigationExtras = {
queryParamsHandling: 'preserve',
preserveFragment: true
};
this.router.navigateByUrl(navigateUrl, navigationExtras);
})
.catch(err => {
console.log(" error in redirecting to the accessable page : " + err);
this.router.navigate(['accessdenied']);
})
}
}
Implement the handleAuthentication function in the okta service class
async handleAuthentication() {
const tokens = await this.oktaAuth.token.parseFromUrl();
this.oktaAuth.tokenManager.add('idToken', tokens.tokens.idToken);
this.oktaAuth.tokenManager.add('accessToken', tokens.tokens.accessToken);
}
Implement isAuthentication function in okta service class
async isAuthenticated() {
try {
let token = await this.oktaAuth.tokenManager.get('idToken')
if (token) {
return true;
} else {
return false;
}
}
catch (e) {
console.log('exception in getting token' + e)
return false;
}
}
Implement authentication guard
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let authenticated = await this.okta.isAuthenticated();
if(authenticated){
return true;
}
localStorage.setItem('appReffererPath', encodeURI(state.url));
this.okta.login();
return false;
}