简体   繁体   中英

Using AWS Amplify Auth on the server with custom auth-storage

I have a server side rendered react application, that invokes Amplify's Auth.CurrentAuthenticatedUser method to check for auth before displaying protected pages.
On the client side I'm using cookieStorage . It works perfectly fine as the credentials are retrieved successfully when invoking Auth.CurrentAuthenticatedUser upon accessing protected routes via react-router's BrowserRouter .
On the server-side (when the protected routes are accessed by a direct http call), I'm using the following configuration for 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
  }
});

I've logged what goes into the setItem and getItem methods and it seems to be retrieving all the information fine when the Auth.CurrentAuthenticatedUser method is invoked, however the method is failing with the error Not Authenticated .

Am I missing something here?

I realised that the Auth.CurrentAuthenticatedUser uses the fetch method under the hood, which is why it was failing. The solution was to provide a fetch method polyfill for node using node-fetch , I did it like so:

const fetch = require('node-fetch');
global.fetch = fetch;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM