amazon-web-services - 如何管理认知令牌生命周期
问题描述
我有一个应用程序将使用 cognito 作为身份验证提供程序。我注意到id 和访问令牌都在一小时后过期。这似乎不是很长时间。
我已经想到了两种管理令牌的方法,但不确定选择哪种/最佳实践。
在向我的后端发出每个请求之前,我可以检查令牌的到期时间,如果它有效,请使用它,如果它无效,我可以使用刷新令牌获取一个新令牌并使用它。
或者
我可以在每个请求中刷新令牌并为请求使用新的 id/访问令牌。
大多数人如何管理这些短暂的代币?
解决方案
使用 cognito,您可以获得 3 种令牌,所有令牌都存储在您的存储中。1)访问令牌。(有效期 1 小时) 2)ID - 令牌。(有效期1小时) 3)刷新令牌。(有效期1个月或2个月请核实)
// 对于网络应用
我已将 AWS-Amplify 用于我的 Web 客户端。
在您的登录页面中,您应该调用 Auth.currentSeesion();
如果访问令牌和 id 令牌的寿命(1 小时)获得 exipers,则调用此方法时,它将查找刷新令牌,然后 aws amplify 将带回访问令牌和 id 令牌并存储到存储中。
链接:https ://aws-amplify.github.io/docs/js/authentication#token-refresh
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.4.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.4.1/umd/react-dom.production.min.js"></script>
useEffect(() => {
analytics.initialize();
// Update Authorization token
auth.currentSession()
.then(data => {
storage.saveDataInLocal(StorageKey.ACCESS_TOKEN, data.idToken.jwtToken);
const { email } = data.idToken.payload;
// checking if user was signed in by gmail
if(props.isGoogleSigned) {
// this code is required to auto login user if he closed the tab last time when he was logined
props.dispatch(sendGoogleSignInRequest(email));
}
props.dispatch(initialCall());
})
.catch(() => {
props.dispatch(initialCall());
});
// Validate user authentication status
auth.currentAuthenticatedUser()
.then(() => {
props.dispatch(fetchAppData());
}
)
.catch(() => {
if (storage.getDataFromLocal(StorageKey.USER_INFO)) {
props.dispatch(clearAppReducer());
storage.clearAllLocalData();
storage.clearAllSessionData();
props.history.push('/login');
}
});
}, []);
推荐阅读
- r - 如何在R中从最高到最低对条形图进行排序?(ggplot2)
- elixir - Elixir Repo.insert_all/2 和唯一约束
- php - 设置 php 变量仅包含选定的数组
- angular - 我在帖子上有一个错误的请求 400
- javascript - How to export the value of an observable and assign to a variable?
- mysql - MySQL - 如何有效地离开基于字段的不同记录(无 n+1)?
- javascript - Using state in child component received from parent component
- jmeter - Jmeter blob上传不允许上传
- sql - Django查询:具有给定电子邮件的所有用户
- ruby-on-rails - 应用 deep_symbolize_keys!散列数组