为了避免将敏感信息存储在本地,并增强安全性,可以使用AWS Amplify自定义身份提供程序来重写AWS Cognito身份服务提供程序。可以使用自定义Authenticator组件来控制令牌存储在哪里,例如在内存中,而不是在本地存储中。
示例代码:
import Authenticator from '@aws-amplify/auth/lib/Authenticator';
class CustomAuthenticator extends Authenticator { // 重写方法来获取令牌并存储在内存中 signIn(username: string, password: string) { return super.signIn(username, password).then(() => { const { attributes } = this.state; const session = attributes.authState; window.sessionStorage.setItem('Auth', session); }); }
signOut() { window.sessionStorage.removeItem('Auth'); return super.signOut(); }
// 重写方法来检查令牌是否存在 checkUser() { const session = window.sessionStorage.getItem('Auth'); if (session) { return true; } return super.checkUser(); } }
import Amplify, { Auth } from 'aws-amplify'; import awsconfig from './aws-exports'; import CustomAuthenticator from './CustomAuthenticator';
Amplify.configure(awsconfig); // 替换默认的Authenticator组件 Auth.configure({ authenticatorComponents: [CustomAuthenticator] });
这样,访问和存储访问令牌的位置就由本地存储改为内存中的会话存储。