3

Я погружаю свои пальцы в неавторизованный/анонимный пользовательский доступ в AWS и надеялся получить сгенерированный токен от Cognito через Lambda.Использование AWS Cognito от Lambda для .NET.

Я не смог заставить его работать в лямбда со следующей ошибкой.

This functionality is not implemented in the portable version of this assembly

{ 
    "errorType": "NotImplementedException", 
    "errorMessage": "This functionality is not implemented in the portable version of this assembly. You should reference the AWSSDK.Core NuGet package from your main application project in order to reference the platform-specific implementation.", 
    "stackTrace": [ 
    "at Amazon.Util.Internal.PlatformServices.ApplicationSettings.GetValue(String key, ApplicationSettingsMode mode)", 
    "at Amazon.CognitoIdentity.CognitoAWSCredentials.GetCachedIdentityId()", 
    "at Amazon.CognitoIdentity.CognitoAWSCredentials..ctor(String accountId, String identityPoolId, String unAuthRoleArn, String authRoleArn, IAmazonCognitoIdentity cibClient, IAmazonSecurityTokenService stsClient)", 
    "at Amazon.CognitoIdentity.CognitoAWSCredentials..ctor(String accountId, String identityPoolId, String unAuthRoleArn, String authRoleArn, RegionEndpoint region)", 
    "at AwsDotnetCsharp.AuthHandler.Get(APIGatewayProxyRequest request, ILambdaContext context)", 
    "at lambda_method(Closure , Stream , Stream , ContextInfo)" 
    ] 
} 

Лямбда является новым C# ядра DotNet версии, а не JavaScript. Я ссылка AWSSDK.Core и AWSSDK.SecurityToken в project.json

Так это CognitoAWSCredentials не совместим (пока) с Dotnet ядром (.net Standard 1.6), который в то время ПИСЬМЕННОГО является версией 3.3.1.1 (https://www.nuget.org/packages/AWSSDK.CognitoIdentity/) подумал на сайте nuget, о котором он говорит.

Мой лямбда-код ... (может быть не прав, но я не могу заставить его работать, чтобы двигаться вперед)

public class AuthHandler 
    { 
     public APIGatewayProxyResponse Get(APIGatewayProxyRequest request, ILambdaContext context) 
     { 
      CognitoAWSCredentials credentials = 
       new CognitoAWSCredentials("us-east-1:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", Amazon.RegionEndpoint.USEast1); 

      var identityPoolId = credentials.GetIdentityIdAsync(); 

      AmazonCognitoIdentityClient cognitoClient = new AmazonCognitoIdentityClient(
       credentials, // the anonymous credentials 
       Amazon.RegionEndpoint.USEast1 // the Amazon Cognito region 
      ); 

      GetIdRequest idRequest = new GetIdRequest(); 
      idRequest.AccountId = "############"; 
      idRequest.IdentityPoolId = identityPoolId.Result; 

      var idResp = cognitoClient.GetIdAsync(idRequest); 

      var id = idResp.Result.IdentityId; 

      var response = new APIGatewayProxyResponse 
      { 
       StatusCode = (int)HttpStatusCode.OK, 
       Body = $"{{ \"{id}\" }}", 
       Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } } 
      }; 

      return response; 
     } 
    } 

Что необходимо, чтобы получить эту работу?

ответ

0

Основная проблема заключается в том, что модуль AWSSDK.Core для .net Framework 4.5 и .net Standard не реализует интерфейс Amazon.Util.Internal.PlatformServices.IApplicationSettings. Сообщение об исключении указывает, что оно реализовано только для версий платформы, таких как Xamarin, Windows Phone и Windows Universal. Вы можете увидеть реализации здесь: https://github.com/aws/aws-sdk-net/tree/master/sdk/src/Core/Amazon.Util/Internal/PlatformServices

Чтобы не использовать объект CognitoAWSCredentials, вам необходимо обходиться, позвонив по телефону AmazonCognitoIdentityClient.

Образец, чтобы получить идентификатор AWS с помощью клиента в https://aws.amazon.com/blogs/mobile/use-amazon-cognito-in-your-website-for-simple-aws-authentication/

// initialize a set of anonymous AWS credentials for our API calls 
AnonymousAWSCredentials cred = new AnonymousAWSCredentials(); 

// initialize the Cognito identity client and prepare a request object 
// to get the identity id 
AmazonCognitoIdentityClient cognitoClient = new AmazonCognitoIdentityClient(
    cred, // the anonymous credentials 
    RegionEndpoint.USEast1 // the Amazon Cognito region 
); 

GetIdRequest idRequest = new GetIdRequest(); 
idRequest.AccountId = "YOUR_AWS_ACCOUNT_ID"; 
idRequest.IdentityPoolId = "YOUR_COGNITO_IDENTITY_POOL_ID"; 
// set the Dictionary of logins if you are authenticating users 
// through an identity provider 
//idRequest.Logins = new Dictionary { 
// { "graph.facebook.com", "FacebookSessionToken" } 
//}; 

// The identity id is in the IdentityId parameter of the response object 
GetIdResponse idResp = cognitoClient.GetId (idRequest); 
Смежные вопросы