Secure Laravel Backend and Angular Frontend with Okta


To integrate Okta authentication and authorization in an application with Laravel (backend) and Angular (frontend), you need to set up both the backend and the frontend to properly handle the authentication and authorization flow. Below are the general steps to integrate Okta with Laravel and Angular.

1. Setting Up Okta

Create an Okta Developer Account:

  • Go to Okta Developer and create a free account.
  • Once logged in, create an Okta Application:
    • For Angular (Frontend): Choose an OAuth 2.0 application with the SPA (Single Page Application) option.
    • For Laravel (Backend): Choose an OAuth 2.0 or OpenID Connect application for API access.

Take note of the following credentials:

  • Client ID
  • Client Secret (for backend)
  • Issuer URL (e.g., https://{yourOktaDomain}/oauth2/default)

2. Integrating Okta in the Angular Frontend

Install Okta SDK in Angular:

Install the required Okta SDK for Angular:

npm install @okta/okta-angular @okta/okta-auth-js

Configure Okta in Angular:

In your app.module.ts, configure Okta authentication.

import { OktaAuthModule } from '@okta/okta-angular';
import { OktaAuthService } from '@okta/okta-auth-js';

@NgModule({
  declarations: [
    // your components
  ],
  imports: [
    // other imports
    OktaAuthModule.initAuth({
      issuer: 'https://{yourOktaDomain}/oauth2/default',
      clientId: '{yourClientId}',
      redirectUri: window.location.origin + '/callback',
      scopes: ['openid', 'profile', 'email'],
    }),
  ],
  providers: [
    OktaAuthService,
    // other providers
  ],
})
export class AppModule {}

Add Routes for Login and Callback:

Set up routes in your app-routing.module.ts to handle login and callback:

import { OktaCallbackComponent, OktaAuthGuard } from '@okta/okta-angular';
import { Routes } from '@angular/router';

const routes: Routes = [
  { path: 'login', component: OktaLoginComponent },
  { path: 'callback', component: OktaCallbackComponent },
  { path: 'profile', component: ProfileComponent, canActivate: [OktaAuthGuard] },
  { path: '**', redirectTo: 'login' }
];

Protect Routes:

Use the OktaAuthGuard to protect routes that require authentication. For example, in your profile.component.ts:

import { OktaAuthService } from '@okta/okta-auth-js';
import { Component } from '@angular/core';

@Component({
  selector: 'app-profile',
  template: `<h1>Welcome to your Profile!</h1>`
})
export class ProfileComponent {
  constructor(private oktaAuth: OktaAuthService) {}
}

3. Integrating Okta in the Laravel Backend

Install Okta SDK in Laravel:

Install Okta’s PHP SDK for authentication via Composer:

composer require okta/jwt-verifier

Configure Laravel to Use Okta:

In config/services.php, add Okta configuration:

'okta' => [
    'client_id' => env('OKTA_CLIENT_ID'),
    'client_secret' => env('OKTA_CLIENT_SECRET'),
    'issuer' => env('OKTA_ISSUER'),
    'audience' => env('OKTA_AUDIENCE'),
],

Then, in your .env file, define Okta settings:

OKTA_CLIENT_ID={yourClientId}
OKTA_CLIENT_SECRET={yourClientSecret}
OKTA_ISSUER=https://{yourOktaDomain}/oauth2/default
OKTA_AUDIENCE={yourAudience}

Handle Authentication in Laravel:

You can now verify Okta JWT tokens in your Laravel controllers. For example, to authenticate requests, you can use a middleware that verifies the JWT sent from the frontend:

use Okta\JwtVerifier\JwtVerifier;
use Illuminate\Http\Request;

class AuthMiddleware
{
    public function handle(Request $request, \Closure $next)
    {
        $jwt = $request->bearerToken();
        if (!$jwt) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        try {
            $jwtVerifier = new JwtVerifier([
                'issuer' => config('services.okta.issuer'),
                'client_id' => config('services.okta.client_id'),
            ]);

            $jwtVerifier->verify($jwt);
        } catch (\Exception $e) {
            return response()->json(['error' => 'Unauthorized: Invalid Token'], 401);
        }

        return $next($request);
    }
}

Protect Routes with Middleware:

In routes/api.php, protect your API routes by applying the middleware to ensure they are secured.

Route::middleware(['auth:api'])->get('/user', function (Request $request) {
    return $request->user();
});

4. Handling Authorization

Authorization can be handled by verifying user roles or permissions in both Angular and Laravel.

  • In Angular: After logging in, you can use Okta's authState$ to determine the user's roles and manage access based on them.
this.oktaAuth.authState$.subscribe(state => {
  if (state.isAuthenticated) {
    // check roles or permissions here
  }
});
  • In Laravel: You can define roles in your Okta account and pass the roles in the JWT. Then, you can use the Gate or Policy classes to handle access control based on roles.
public function handle(Request $request, \Closure $next)
{
    $user = $request->user(); // Get user from JWT

    if (!$user->hasRole('admin')) {
        return response()->json(['error' => 'Forbidden'], 403);
    }

    return $next($request);
}

5. Testing the Integration

Once both parts are set up, you can:

  1. Log in via Okta from Angular and get the JWT.
  2. Send requests to the Laravel API with the JWT in the Authorization header.
  3. Ensure the Laravel API is correctly verifying the JWT and returning data based on the user's roles and permissions.

By following the steps above, you can successfully integrate Okta authentication and authorization between your Angular frontend and Laravel backend. Okta handles user authentication, and you can securely communicate between your frontend and backend using JWT tokens for access control.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete