使用 AWS Amplify 通过网站登录 chrome 扩展程序



我正在构建一个Chrome扩展程序,并正在尝试实现用户登录和注册。我最初在Chrome扩展程序的弹出部分中具有注册和登录功能,但是,在检查了一些更流行的chrome扩展程序(如Grammarly和Honey(之后,我意识到他们使用他们的网站登录和注册用户。出于各种原因,我决定也这样做。

我正在为我的网站和弹出窗口使用 React js。我正在使用 AWS-Amplify 来处理登录、注册和用户会话。当我打开弹出窗口时,我让它在使用await Auth.signIn(email, password);登录我的网站后使用await Auth.currentSession();检查用户会话。但是,这行不通。我已经阅读了 Amplify 文档,但找不到答案。我的弹出窗口中有需要访问 AWS 服务的功能。

如何使用 AWS-Amplify 通过我的网站登录我的 chrome 扩展程序?

我最终还是想通了。我不确定这是否是执行此操作的"正确方法",但它有效。在我的反应网络应用程序上使用 amplify 登录后,我可以抓取会话并将其发送到 chrome 扩展程序。但是,只能通过扩展消息传递 API 发送 JSONifible 对象。因此,会话附带的所有功能都将丢失。但是,您可以从可通过消息传递 API 发送的信息重新生成会话。重新生成会话,创建新的 CognitoUser 对象,然后将会话附加到用户。完成后,会话将被存储,Ampify将能够使用它。

在网络方面。

//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);     
});

在后台的扩展端.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.
}

AWS Amplify 中有一个配置选项,您可以在其中覆盖默认令牌存储(浏览器中的本地存储(

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
});

更多信息在这里

你可以做的是这样的事情,使用chrome.storeAPI

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");
})
}
}

这是我在解决完全相同的问题时提出的解决方案。我希望这也对你有用:https://github.com/vocably/pontis

如何使用它

npm install --save @vocably/pontis
// website-app/index.js
import { Auth } from '@aws-amplify/auth';
import { AppAuthStorage } from '@vocably/pontis';
const extensionId = 'baocigmmhhdemijfjnjdidbkfgpgogmb';
Auth.configure({
// The following line sets up the custom storage
// which exchages auth tokens with the extension
storage: new AppAuthStorage(extensionId),
// and the rest of Auth params:
region: 'eu-central-1',
userPoolId: 'eu-central-1_uSErPooL',
//etc...
});
// extension/service-worker.js
import { registerExtensionStorage } from '@vocably/pontis';
import { Auth } from '@aws-amplify/auth';
// The only function param is responsible for
// the storage type. It could be 'sync' or 'local'
const storage = registerExtensionStorage('sync');
Auth.configure({
// The following line sets up the custom extension
// storage which exchanges Auth tokens with the app
storage: storage,
// and the rest of Auth params:
region: 'eu-central-1',
userPoolId: 'eu-central-1_uSErPooL',
//etc...
});

就是这样。

最新更新