Prabu Bai
Prabu Bai

Reputation: 1

OKTA implementation IONIC 3 Angular 5 without plugin and node package

facing issue in angular OIDC and @okta/okta-auth-js version version compatibility issue

If you need to implement OKTA authentication in an Ionic 3 Angular 5 application without using the OKTA JavaScript SDK or any node package, you can still do so by leveraging OKTA’s API endpoints directly. This approach involves manually handling the OAuth 2.0 flow using HTTP requests.

Here’s a step-by-step guide to implementing OKTA authentication manually:

1. Set Up OKTA

  1. Create an OKTA Developer Account:

  2. Create an Application:

    • Once logged in, navigate to Applications and create a new application.
    • Choose SPA (Single Page Application) for the platform.
    • Configure the application settings and note down the Client ID, Issuer URL, and Redirect URI.

2. Implement Authentication in Your App

1. Configure Your Environment:

Add your OKTA configuration to an environment file, such as src/environments/environment.ts.

export const environment = {
  production: false,
  oktaConfig: {
    issuer: 'https://{yourOktaDomain}/oauth2/default',
    clientId: '{yourClientId}',
    redirectUri: 'http://localhost:8100/callback',
    scopes: ['openid', 'profile', 'email'],
    authorizationEndpoint: 'https://{yourOktaDomain}/oauth2/default/v1/authorize',
    tokenEndpoint: 'https://{yourOktaDomain}/oauth2/default/v1/token',
    userInfoEndpoint: 'https://{yourOktaDomain}/oauth2/default/v1/userinfo',
  }
};

2. Create an Authentication Service:

Create a service to handle authentication logic. For example, auth.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../environments/environment';
import { Observable, of } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class AuthService {
  private authUrl = environment.oktaConfig.authorizationEndpoint;
  private tokenUrl = environment.oktaConfig.tokenEndpoint;
  private userInfoUrl = environment.oktaConfig.userInfoEndpoint;

  constructor(private http: HttpClient) { }

  login(username: string, password: string): void {
    const params = new URLSearchParams();
    params.set('grant_type', 'password');
    params.set('username', username);
    params.set('password', password);
    params.set('client_id', environment.oktaConfig.clientId);
    params.set('redirect_uri', environment.oktaConfig.redirectUri);
    params.set('scope', environment.oktaConfig.scopes.join(' '));

    const body = params.toString();
    const headers = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });

    this.http.post(this.tokenUrl, body, { headers }).pipe(
      tap((response: any) => this.storeTokens(response)),
      catchError(this.handleError<any>('login'))
    ).subscribe();
  }

  private storeTokens(response: any) {
    // Store the access and ID tokens
    localStorage.setItem('access_token', response.access_token);
    localStorage.setItem('id_token', response.id_token);
  }

  logout() {
    localStorage.removeItem('access_token');
    localStorage.removeItem('id_token');
    window.location.href = environment.oktaConfig.issuer + '/v1/logout?returnTo=' + environment.oktaConfig.redirectUri;
  }

  getUserInfo(): Observable<any> {
    const accessToken = localStorage.getItem('access_token');
    const headers = new HttpHeaders({ 'Authorization': `Bearer ${accessToken}` });

    return this.http.get(this.userInfoUrl, { headers }).pipe(
      catchError(this.handleError<any>('getUserInfo'))
    );
  }

  private handleError<T>(operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(`${operation} failed: ${error.message}`);
      return of(result as T);
    };
  }
}

3. Handle Authentication in Components:

In your login.page.ts:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  username: string;
  password: string;

  constructor(private authService: AuthService, private navCtrl: NavController) { }

  login() {
    this.authService.login(this.username, this.password);
    // Redirect to another page if login is successful
  }
}

4. Handle Callback Route:

Create a page to handle the OKTA callback, for example, callback.page.ts:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AuthService } from '../../services/auth.service';

@Component({
  selector: 'page-callback',
  templateUrl: 'callback.html',
})
export class CallbackPage {
  constructor(private authService: AuthService, private navCtrl: NavController) { }

  ngOnInit() {
    // Optionally handle any tokens or data returned in the URL fragment
    this.navCtrl.setRoot('home'); // Navigate to home page
  }
}

5. Configure Routing:

Ensure your routing or page navigation includes the CallbackPage.

3. Test Your Application

Notes:

  1. Security: Storing tokens in local storage can expose them to potential attacks. For more secure applications, consider using secure storage mechanisms and implementing proper token expiration handling.

  2. CORS Issues: Direct HTTP requests from your application may encounter CORS issues. Ensure that OKTA is configured to allow requests from your application's domain.

By following these steps, you should be able to implement OKTA authentication in your Ionic 3 Angular 5 application without relying on the OKTA SDK or additional node packages.

This one correct?

Upvotes: 0

Views: 24

Answers (0)

Related Questions