How to pass data from one application to other applicaton Angular?

38 Views Asked by At

I must transfer data between two Angular applications that are installed on different domains because of a necessity. Allow me to illustrate with an example:

For example, suppose App1 is available at https://app1.com and App2 is available at https://app2.com.

I utilize App1 for authentication, and after the user logs in successfully, I have to send them to App2 so they may do some tasks there.

Without utilizing the query parameters, I must pass the token from App1 to App2.

Is there a way to make this happen? I've read other such questions on Stackoverflow, but they weren't answered.

2

There are 2 best solutions below

1
Agustín Larrubia On

I think you can do that with a 'Factory function' in your provider (https://angular.io/api/core/FactoryProvider) at app.modules and 'canActivate' in your routes (https://angular.io/api/router/CanActivate) with AuthGuard. The asnwer is not complete but It might help :D

0
codewithharshad On

One common approach to achieve this kind of cross-domain data transfer without using query parameters is through the use of JSON Web Tokens (JWT);

  1. Authentication on App1: When the user logs in to App1, generate a JWT containing relevant authentication information, such as user ID, roles, etc. Sign this JWT using a secret key known only to App1.
  2. Redirect to App2: After successful authentication on App1, redirect the user to App2, passing the JWT in the request headers or as a cookie.
  3. Verify JWT on App2: App2 receives the JWT in the request headers or cookies. Verify the JWT's signature using the secret key shared with App1. If the signature is valid, extract the authentication information and use it to authenticate the user on App2.

Example :

App 1

import { JwtService } from 'jwt-service-library';

// Generate JWT upon successful login
const payload = { userId: '123', username: 'example_user' };
const token = JwtService.sign(payload, 'secret_key');

App 2

import { JwtService } from 'jwt-service-library';

// Receive JWT and verify
const token = request.headers['authorization'];
const payload = JwtService.verify(token, 'secret_key');

// Authenticate user based on payload
const userId = payload.userId;
// Perform authentication logic using userId