如何使用Cognito for Android刷新访问令牌?文档建议如下(https://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-android-sdk.html):
// Implement authentication handler
AuthenticationHandler handler = new AuthenticationHandler {
@Override
public void onSuccess(CognitoUserSession userSession) {
// Authentication was successful, the "userSession" will have the current valid tokens
// Time to do awesome stuff
}
@Override
public void getAuthenticationDetails(final AuthenticationContinuation continuation, final String userID) {
// User authentication details, userId and password are required to continue.
// Use the "continuation" object to pass the user authentication details
// After the user authentication details are available, wrap them in an AuthenticationDetails class
// Along with userId and password, parameters for user pools for Lambda can be passed here
// The validation parameters "validationParameters" are passed in as a Map<String, String>
AuthenticationDetails authDetails = new AuthenticationDetails(userId, password, validationParameters);
// Now allow the authentication to continue
continuation.setAuthenticationDetails(authDetails);
continuation.continueTask();
}
@Override
public void getMFACode(final MultiFactorAuthenticationContinuation continuation) {
// Multi-factor authentication is required to authenticate
// A code was sent to the user, use the code to continue with the authentication
// Find where the code was sent to
String codeSentHere = continuation.getParameter()[0];
// When the verification code is available, continue to authenticate
continuation.setMfaCode(code);
continuation.continueTask();
}
@Override
public void authenticationChallenge(final ChallengeContinuation continuation) {
// A custom challenge has to be solved to authenticate
// Set the challenge responses
// Call continueTask() method to respond to the challenge and continue with authentication.
}
@Override
public void onFailure(final Exception exception) {
// Authentication failed, probe exception for the cause
}
};
user.getSession(handler);
这里是为什么这不起作用。当令牌过期时,我正在获取会话的用户对象不再经过身份验证。因此,通过以下方式检索缓存的用户,将返回null
CognitoUser user = userPool.getCurrentUser();
因为上面返回null,我尝试通过id
获取用户对象CognitoUser user = userPool.getUser(userId);
它工作得很好,只是用户没有经过身份验证,并且在接下来的回调阶段会失败,因为userID为空
@Override
public void getAuthenticationDetails(final AuthenticationContinuation continuation, final String userID)
只有当我在令牌过期之前尝试此调用时才会执行此操作,并且我可以接收新的访问令牌。但是,在令牌过期后,如何做到这一点呢?对此任何帮助都将不胜感激。提前感谢
当您调用getSession(…)-获取令牌-并且如果缓存的令牌已经过期,SDK将自动刷新令牌(只要刷新令牌没有过期)。如果刷新令牌也已过期,则调用getAuthenticationDetails(…),因为现在需要用户凭据(用户名、密码等)来获取一组新的令牌。无论你如何获得用户对象,即通过getCurrentUser()或getUser(…)方法,只要有有效的缓存令牌或如果令牌可以刷新,你将获得有效的令牌与getSession(…)。
使用最新SDK (ver 2.3.1)重试