我已经设置了Xamarin平台应用程序,该应用程序可以通过有效的AWS Cognito用户池处理用户登录。但是,当我尝试访问其他AWS服务时,会收到“无效的登录令牌”。错误。
在AWS控制台中,我已经设置了带有App Client的用户池以及使用Cognito作为身份验证提供程序的身份池:
编辑身份池>展开身份验证提供程序选项卡>认知选项卡>将我的用户池ID和应用程序客户端ID添加到必填字段。
我处理登录的代码片段如下:
private AmazonCognitoIdentityProviderClient provider;
public AmazonCognitoIdentityProviderClient Provider
{
get
{
if(provider == null)
{
provider = new AmazonCognitoIdentityProviderClient(cognitoAWSCredentials, Constants.REGION_ENDPOINT);
}
return provider;
}
}
private CognitoUserPool userPool;
public CognitoUserPool UserPool
{
get
{
if(userPool == null)
{
userPool = new CognitoUserPool(Constants.AWS_COGNITO_USER_POOL_ID, Constants.AWS_COGNITO_APP_CLIENT_ID, Provider);
}
return userPool;
}
}
private CognitoAWSCredentials cognitoAWSCredentials;
public CognitoAWSCredentials CognitoAWSCredentials
{
get
{
if (cognitoAWSCredentials == null)
{
cognitoAWSCredentials = new CognitoAWSCredentials(Constants.AWS_COGNITO_USER_IDENTITY_POOL_ID, Constants.REGION_ENDPOINT);
}
return cognitoAWSCredentials;
}
}
private async void GetAWSCredentials()
{
string accesstoken = string.Empty;
// Try to find user;
CognitoUser user = new CognitoUser(usernameField.Text, Constants.AWS_COGNITO_APP_CLIENT_ID, UserPool, Provider);
InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
{
Password = passwordField.Text
};
try
{
AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest);
}
catch(Exception ex)
{
string message = ex.Message;
if(message == "User does not exist.")
{
await DisplayAlert("Error", message, "Ok");
}
else if(message == "Incorrect username or password.")
{
await DisplayAlert("Error", "Incorrect password.", "Ok");
}
else
{
await DisplayAlert("Error", "Oops! Something went wrong. Please try again.", "Ok");
}
loginButton.IsEnabled = true;
return;
}
CognitoAWSCredentials.AddLogin("www.amazon.com", user.SessionTokens.IdToken);
}
每当我尝试使用上述代码使用其他任何AWS服务(在本例中为DynamoDB)时,我都会不断收到以下错误消息:
“向https://cognito-identity.ap-southeast-2.amazonaws.com/发送ERROR | NotAuthorizedException请求GetIdRequest。尝试1。-> Amazon.CognitoIdentity.Model.NotAuthorizedException:无效的登录令牌。”
如何使用适用于Xamarin的AWS Cognito对用户进行正确的身份验证?
任何帮助将不胜感激。 谢谢。