Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
Login to chrome extension via website with AWS amplify

I'm building a chrome extension and am trying to implement user login and sign-up. I originally had the sign-up and login functionality in the popup portion of my chrome extension but, after examining some of the more popular chrome extensions like Grammarly and Honey, I realized that they use their websites to login and sign up users. I decided to do the same for various reasons.

I'm using React js for both my website and the popup. I am using AWS-Amplify to handle login, sign-up, and user sessions. When I open the popup I have it check for a user session using await Auth.currentSession(); after having logged in on my site with await Auth.signIn(email, password);. However, that doesn't work. I've read the Amplify docs but couldn't find an answer. I have functionality in my popup that requires access to AWS services.

How can I use AWS-Amplify to login to my chrome extension via my website?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

I did end up figuring this out. I'm not sure if this is the "right way" to do this but it works. After logging in using amplify on my react web app I can grab the session and send it to the chrome extension. However, only JSONifible objects can be sent through the extension messaging api. So all the functions that come with the session are lost. However, you can rebuild the session from the information that can be sent through the messaging api. You rebuild the session, create a new CognitoUser object, and then attach the session to the user. Once that is done the session will be stored and amplify will be able to use it.

On the web side.

//Get the current session from aws amplify
const session = await Auth.currentSession();


const extensionId = 'your_extension_id';

chrome.runtime.sendMessage(extensionID, session,
        function(response) {
            // console.log(response);     
        });

On the extension side in background.js

// This is all needed to reconstruct the session
import {
    CognitoIdToken, 
    CognitoAccessToken, 
    CognitoRefreshToken, 
    CognitoUserSession,
    CognitoUser,
    CognitoUserPool
  } from "amazon-cognito-identity-js";
import {Auth} from "aws-amplify";

//Listen for incoming external messages.
chrome.runtime.onMessageExternal.addListener(
  async function (request, sender, sendResponse) {
    if (request.session) {
      authenticateUser(request.session);;
    } else {
      console.log(request);
    }
    sendResponse("OK")
  });

//Re-build the session and authenticate the user
export const authenticateUser = async (session) => {
    let idToken = new CognitoIdToken({
      IdToken: session.idToken.jwtToken
    });
    let accessToken = new CognitoAccessToken({
        AccessToken: session.accessToken.jwtToken
    });
    let refreshToken = new CognitoRefreshToken({
        RefreshToken: session.refreshToken.token
    });
    let clockDrift = session.clockDrift;
    const sessionData = {
      IdToken: idToken,
      AccessToken: accessToken,
      RefreshToken: refreshToken,
      ClockDrift: clockDrift
    }
    // Create the session
    let userSession  = new CognitoUserSession(sessionData);
    const userData = {
      Username: userSession.getIdToken().payload['cognito:username'],
      Pool: new CognitoUserPool({UserPoolId: YOUR_USER_POOL_ID, ClientId: YOUR_APP_CLIENT_ID})
    }
    
    // Make a new cognito user
    const cognitoUser = new CognitoUser(userData);
    // Attach the session to the user
    cognitoUser.setSignInUserSession(userSession);
    // Check to make sure it works
    cognitoUser.getSession(function(err, session) {
      if(session){
        //Do whatever you want here
      } else {
        console.error("Error", err);
      }
      
    })
    // The session is now stored and the amplify library can access it to do
    // whatever it needs to.
  }
over 4 years ago · Santiago Trujillo Relatório

0

There is a configuration option in AWS Amplify where you can override the default token storage (which is localStorage in the browser)

class MyStorage {
    // the promise returned from sync function
    static syncPromise = null;
    // set item with the key
    static setItem(key: string, value: string): string;
    // get item with the key
    static getItem(key: string): string;
    // remove item with the key
    static removeItem(key: string): void;
    // clear out the storage
    static clear(): void;
    // If the storage operations are async(i.e AsyncStorage)
    // Then you need to sync those items into the memory in this method
    static sync(): Promise<void> {
        if (!MyStorage.syncPromise) {
            MyStorage.syncPromise = new Promise((res, rej) => {});
        }
        return MyStorage.syncPromise;
    }
}

// tell Auth to use your storage object
Auth.configure({
    // REQUIRED - Amazon Cognito Region
    region: process.env.REACT_APP_AWS_REGION,

    // OPTIONAL - Amazon Cognito User Pool ID
    userPoolId: process.env.REACT_APP_COGNITO_USER_POOL_ID,

    // OPTIONAL - Amazon Cognito Web Client ID (26-char alphanumeric string)
    userPoolWebClientId: process.env.REACT_APP_COGNITO_USER_POOL_CLIENT_ID,

    // OPTIONAL - customized storage object
    storage: MyStorage
});

More information here

What you could do is something like this, using chrome.store API

export class TokensStorage {
  static setItem(key, value) {
    chrome.storage.local.set({[key]: JSON.stringify(value)}, () => {
      console.log('token stored');
    });
  }
  // get item with the key
  static getItem(key) {
    return new Promise((resolve, reject) => {
      chrome.storage.local.get([key], (result) =>  {
        resolve(result)
      });
    })
  }
  // remove item with the key
  static removeItem(key) {
    chrome.storage.local.remove(key, () => {
      console.log("item removed");
    })
  }
  // clear out the storage
  static clear() {
    chrome.storage.local.clear(() => {
      console.log("storage cleared");
    })
  }
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda