#(Self-Hosted) OAuth workaround iframe

27 messages · Page 1 of 1 (latest)

teal vigil
#

Hello,
I have a few questions regarding my angular application that uses Appwrite and is intended to run inside an iframe of a SharePoint web part.

As I want to run the application in SharePoint, I have created a WebPart the integrates the application via an iframe. I am using Appwrites authentication and would like to use Microsoft OAuth. However, I understand that this is not possible inside an iframe.

Currently, as a workaround I can get the OAuth access token via the WebPart and pass it to the angular application. This is as far as I get, as I have no idea on how to start a session for the correct user using the appwrite api with the access token.

Therefore, I was wondering if the workaround as I have envisioned it is even possible. If, yes, how would I continue the login process? If, no, is there another / better workaround possible? Any help is appreciated!

Thanks in advance!

clever crescent
#

Hello! I understand your situation. Integrating Appwrite authentication within an iframe in a SharePoint web part can be tricky, especially with OAuth. Here’s a possible approach:

  1. Retrieve OAuth Token: As you mentioned, you can get the OAuth access token via the SharePoint web part.
    https://appwrite.io/docs/products/auth/oauth2

  2. Pass Token to Angular App: Send the token to your Angular application running inside the iframe using postMessage.

  3. Create Session in Appwrite: Use the Appwrite API to create a session for the user using the access token.
    https://appwrite.io/docs/products/auth/custom-token
    https://appwrite.io/docs/references/cloud/models/session

#

Basic Example of code like how can you do that

const sdk = require('node-appwrite');

// Initialize the Appwrite client
const client = new sdk.Client();
client
    .setEndpoint('YOUR_ENDPOINT') // Your API Endpoint
    .setProject('YOUR_PROJECT_ID') // Your project ID
    .setKey('YOUR_API_KEY'); // Your API key

const database = new sdk.Database(client);

// Function to create a session using the access token
async function createSessionWithToken(token) {
    const sessionClient = new sdk.SessionClient(client);
    const session = await sessionClient.createSession({
        token: token,
    });
    return session;
}

// Example usage
const accessToken = 'YOUR_ACCESS_TOKEN'; // Replace with the actual token
createSessionWithToken(accessToken)
    .then(session => {
        console.log('Session created:', session);
    })
    .catch(error => {
        console.error('Error creating session:', error);
    });
#

Lastly,
4) Handle Session: Once the session is created, you can use it to authenticate the user and access their data.

#

In short: To integrate your Angular application inside an iframe in a SharePoint web part using Appwrite's authentication with Microsoft OAuth, follow these steps: Retrieve the OAuth token from your SharePoint web part. Pass the token to your Angular app running inside the iframe using JavaScript postMessage. In Angular, set up an event listener with Renderer2 to capture the token message from the parent window. Process the token in your Angular app. Finally, use the token to authenticate and create a session with Appwrite. This process helps bypass iframe restrictions and ensures secure user authentication within your embedded Angular application.

teal vigil
#

@clever crescent Thank you for your quick reply!! I will try that out immediately.

#

However, I have a quick question to step 3: I see you are using the server sdk to create the session. Would it be possible to achieve the same in the client sdk?

clever crescent
#
import { Client, Account } from 'appwrite';

const client = new Client()
  .setEndpoint('YOUR_API_ENDPOINT')
  .setProject('YOUR_PROJECT_ID');

const account = new Account(client);

async function createSessionWithToken(token: string) {
  try {
    const session = await account.createOAuth2Session(
      'microsoft',
      token,
      'YOUR_REDIRECT_URL'
    );
    console.log('Session created:', session);
  } catch (error) {
    console.error('Error creating session:', error);
  }
}
#

Example Usage:

import { Component, OnInit } from '@angular/core';
import { Client, Account } from 'appwrite';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  private client: Client;
  private account: Account;

  constructor() {
    this.client = new Client()
      .setEndpoint('YOUR_API_ENDPOINT')
      .setProject('YOUR_PROJECT_ID');
    this.account = new Account(this.client);
  }

  ngOnInit() {
    window.addEventListener('message', (event) => {
      if (event.origin === 'YOUR_SHAREPOINT_URL') {
        const token = event.data.token;
        this.createSessionWithToken(token);
      }
    });
  }

  async createSessionWithToken(token: string) {
    try {
      const session = await this.account.createOAuth2Session(
        'microsoft',
        token,
        'YOUR_REDIRECT_URL'
      );
      console.log('Session created:', session);
    } catch (error) {
      console.error('Error creating session:', error);
    }
  }
}
teal vigil
#

@clever crescent Thanks for the Tipps! I am currently trying to test it, but I keep on getting redirection errors from Microsoft for the oAuth. I am using Appwrite to create an oAuthSession in the webpart via: account.createOAuth2Session(OAuthProvider.Microsoft, "[pathToSharePointSite]", "[pathToSharePointSite]");
I have the [pathToSharePointSite] added to the redirect URIs in Microsoft Entra. Yet, the error I get is:
AADSTS50011: The redirect URI 'http://localhost/v1/account/sessions/oauth2/callback/microsoft/[projectId]' specified in the request does not match the redirect URIs configured [...]
I am unsure how i can set the correct redirect uri for the oAuth, as it seems to ignore the ones in the function call.
Maybe you have an idea😅.
Cheers!

teal vigil
clever crescent
#

Ensure the exact URI including your Appwrite project ID is registered in Microsoft Entra’s App Registration.
The issue is regarding mismatch of redirect URI

teal vigil
teal vigil
#

account.createOAuth2Session(OAuthProvider.Microsoft, "[pathToSharePointSite]", "[pathToSharePointSite]"); This is my entire code for the webpart inside the render function so far. Nothing else has been added to the webpart. Everything else is setup in either in Microsoft or Appwrite.

clever crescent
#

Since your app is self-hosted, where did you deploy it? Docker, Kubernetes, or manual deployment?

teal vigil
#

It is currently running in Docker

clever crescent
teal vigil
#

These are the logs I am getting in the appwrite container:
appwrite | [Error] Timestamp: 2024-10-22T14:42:43+00:00 appwrite | [Error] Method: GET appwrite | [Error] URL: /v1/account/sessions/oauth2/:provider/redirect appwrite | [Error] Type: TypeError appwrite | [Error] Message: Cannot assign null to property Appwrite\Auth\OAuth2\Microsoft::$tokens of type array appwrite | [Error] File: /usr/src/code/src/Appwrite/Auth/OAuth2/Microsoft.php appwrite | [Error] Line: 6

clever crescent
#

It looks like there’s a null assignment issue causing the 500 error.

#

Can you re-check Ouath token is currectly retrived from microsoft and not showing null value

#

Edit the Microsoft OAuth2 File in your appwrite setup, add logs before & after the token assignment to see if the token is being correctly retrieved

teal vigil
clever crescent
#

let's continue this in dm either this post will have 100+ messages