在具有自定义授权存储的服务器上使用 AWS Amplify Auth
Using AWS Amplify Auth on the server with custom auth-storage
我有一个服务器端呈现的 React 应用程序,它调用 Amplify 的 Auth.CurrentAuthenticatedUser
方法在显示受保护的页面之前检查身份验证。
在客户端,我使用 cookieStorage
。它工作得很好,因为在通过 react-router 的 BrowserRouter
访问受保护路由时调用 Auth.CurrentAuthenticatedUser
时成功检索了凭据。
在服务器端(当通过直接 http 调用访问受保护的路由时),我使用以下配置进行 Amplify:
import cookie from 'cookie';
class ServerCookieStorage {
constructor(requestCookie) {
this.cookieObj = {};
if (requestCookie) this.cookieObj = cookie.parse(requestCookie);
}
setItem(key, value) {
this.cookieObj[key] = value;
}
getItem(key) {
return this.cookieObj[key];
}
removeItem(key) {
this.cookieObj[key] = '';
}
}
Amplify.configure({
Auth: {
identityPoolId: 'placeholder',
region: 'placeholder',
userPoolId: 'placeholder',
userPoolWebClientId: 'placeholder',
storage: new ServerCookieStorage(event.headers.Cookie);
//cookie header in aws lambda functions is located in event.header.Cookie
}
});
我已经记录了进入 setItem
和 getItem
方法的内容,当调用 Auth.CurrentAuthenticatedUser
方法时似乎可以正常检索所有信息,但是该方法是因错误 Not Authenticated
.
而失败
我是不是漏掉了什么?
我意识到 Auth.CurrentAuthenticatedUser
在幕后使用了 fetch
方法,这就是它失败的原因。解决方案是使用 node-fetch
为节点提供 fetch
方法 polyfill,我是这样做的:
const fetch = require('node-fetch');
global.fetch = fetch;
我有一个服务器端呈现的 React 应用程序,它调用 Amplify 的 Auth.CurrentAuthenticatedUser
方法在显示受保护的页面之前检查身份验证。
在客户端,我使用 cookieStorage
。它工作得很好,因为在通过 react-router 的 BrowserRouter
访问受保护路由时调用 Auth.CurrentAuthenticatedUser
时成功检索了凭据。
在服务器端(当通过直接 http 调用访问受保护的路由时),我使用以下配置进行 Amplify:
import cookie from 'cookie';
class ServerCookieStorage {
constructor(requestCookie) {
this.cookieObj = {};
if (requestCookie) this.cookieObj = cookie.parse(requestCookie);
}
setItem(key, value) {
this.cookieObj[key] = value;
}
getItem(key) {
return this.cookieObj[key];
}
removeItem(key) {
this.cookieObj[key] = '';
}
}
Amplify.configure({
Auth: {
identityPoolId: 'placeholder',
region: 'placeholder',
userPoolId: 'placeholder',
userPoolWebClientId: 'placeholder',
storage: new ServerCookieStorage(event.headers.Cookie);
//cookie header in aws lambda functions is located in event.header.Cookie
}
});
我已经记录了进入 setItem
和 getItem
方法的内容,当调用 Auth.CurrentAuthenticatedUser
方法时似乎可以正常检索所有信息,但是该方法是因错误 Not Authenticated
.
我是不是漏掉了什么?
我意识到 Auth.CurrentAuthenticatedUser
在幕后使用了 fetch
方法,这就是它失败的原因。解决方案是使用 node-fetch
为节点提供 fetch
方法 polyfill,我是这样做的:
const fetch = require('node-fetch');
global.fetch = fetch;