Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Repo info
Activity
    alexgsingh
    @alexgsingh

    Hi all, I am trying to use Amazon.Extensions.CognitoAuthentication library. I can authenticate a user with the user in Cognito Userpool but then when trying to upload to s3 using an Identitypool, I get the following error. Please advise? FYI I am using .net c# in Xamarin

    at Amazon.S3.Util.BucketRegionDetector.GetUsEast1ClientFromCredentials (Amazon.Runtime.ImmutableCredentials credentials) [0x00000] in <f978334983bd4d62a4fa9583dc601968>:0
    at Amazon.S3.Util.BucketRegionDetector.GetHeadBucketPreSignedUrl (System.String bucketName, Amazon.Runtime.ImmutableCredentials credentials) [0x00000] in <f978334983bd4d62a4fa9583dc601968>:0
    at Amazon.S3.Util.BucketRegionDetector.GetBucketRegionNoPipelineAsync (System.String bucketName, Amazon.Runtime.ImmutableCredentials credentials) [0x0000a] in <f978334983bd4d62a4fa9583dc601968>:0
    at Amazon.S3.Util.BucketRegionDetector.DetectMismatchWithHeadBucketFallbackAsync (Amazon.S3.Util.AmazonS3Uri requestedBucketUri, Amazon.Runtime.AmazonServiceException serviceException, Amazon.Runtime.ImmutableCredentials credentials) [0x00092] in <f978334983bd4d62a4fa9583dc601968>:0
    at Amazon.S3.Internal.AmazonS3RetryPolicy.SharedRetryForExceptionAsync (Amazon.Runtime.IExecutionContext executionContext, System.Exception exception, System.Func3[T1,T2,TResult] retryForExceptionSync, System.Func3[T1,T2,TResult] baseRetryForException) [0x000e2] in <f978334983bd4d62a4fa9583dc601968>:0
    at Amazon.S3.Internal.AmazonS3RetryPolicy.RetryForExceptionAsync (Amazon.Runtime.IExecutionContext executionContext, System.Exception exception) [0x00091] in <f978334983bd4d62a4fa9583dc601968>:0
    at Amazon.Runtime.RetryPolicy.RetryAsync (Amazon.Runtime.IExecutionContext executionContext, System.Exception exception) [0x000ed] in <3be753f269f04a3baa3e67389f87b6c2>:0
    at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T] (Amazon.Runtime.IExecutionContext executionContext) [0x001fd] in <3be753f269f04a3baa3e67389f87b6c2>:0
    at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T] (Amazon.Runtime.IExecutionContext executionContext) [0x00080] in <3be753f269f04a3baa3e67389f87b6c2>:0
    at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T] (Amazon.Runtime.IExecutionContext executionContext) [0x00080] in <3be753f269f04a3baa3e67389f87b6c2>:0
    at Amazon.S3.Internal.AmazonS3ExceptionHandler.InvokeAsync[T] (Amazon.Runtime.IExecutionContext executionContext) [0x00099] in <f978334983bd4d62a4fa9583dc601968>:0
    at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T] (Amazon.Runtime.IExecutionContext executionContext) [0x00099] in <3be753f269f04a3baa3e67389f87b6c2>:0
    at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T] (Amazon.Runtime.IExecutionContext executionContext) [0x000ab] in <3be753f269f04a3baa3e67389f87b6c2>:0
    at Amazon.S3.Transfer.Internal.SimpleUploadCommand.ExecuteAsync (System.Threading.CancellationToken cancellationToken) [0x00120] in <f978334983bd4d62a4fa9583dc601968>:0
    at MobileAnalyser.Services.S3DataStore.AddItemAsync (System.String filePath, System.String key, System.Threading.CancellationToken token)

    Jonas Steinberg
    @jonassteinberg1
    is there a way to specify a proxy bypass? I have some domains that when requested should not be proxied to, e.g. s3.amazonaws.com (because of course this has a vpc endpoint)
    Fagro Vizcaino
    @fagro-vizcaino
    Hi Guys

    I'm getting this error after I spend a few minutes on the Amazon Cognito Login Page of my app and then try to login:

    System.Exception: An error was encountered while handling the remote login. ---> System.Exception: Correlation failed.
    --- End of inner exception stack trace ---
    at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
    at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
    at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
    at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
    at Cbord.LandingPage.Web.Startup.<>c.<<Configure>b__6_0>d.MoveNext() in /src/LandingPage/LandingPage.Web/Startup.cs:line 306
    --- End of stack trace from previous location where exception was thrown ---
    at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

    Can you please point me in the right direction ?

    Fagro Vizcaino
    @fagro-vizcaino
    This is my Startup.cs:
     services.AddScoped<IViewRenderService, ViewRenderService>();
    
                services.AddMvc()
                    .AddViewLocalization()
                        .AddDataAnnotationsLocalization()
                    .AddJsonOptions(options =>
                    {
                        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    });
    
                services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
                services.AddAuthorization(options =>
                {
                    //Temporary Authorization FIX - added roles policy (to test roles), while AwsCognito - policy not implemented
                    options.AddPolicy("RequireRoles",
                        policy => policy.RequireRole("SysAdmin", "OrgAdmin", "PhiUser", "User"));
                });
    
                services.AddScoped<ILandingPageUserService, LandingPageUserService>();
                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
                })
                    .AddCookie(options =>
                    {
                        //options.Cookie.SecurePolicy = mEnvironment.IsDevelopment()
                        //    ? CookieSecurePolicy.None
                        //    : CookieSecurePolicy.Always;
                        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                        options.Cookie.SameSite = SameSiteMode.None;
                        options.Cookie.Expiration = TimeSpan.FromMinutes(4.5);
                    })
                    .AddOpenIdConnect(options =>
                    {
                        options.ResponseType = Configuration["Authentication:Cognito:ResponseType"];
                        options.MetadataAddress = Configuration["Authentication:Cognito:MetadataAddress"];
                        options.ClientId = Configuration["Authentication:Cognito:ClientId"];
                        //options.CallbackPath = new PathString(Configuration["Authentication:Cognito:CallbackUrl"]);
                        options.SaveTokens = bool.Parse(Configuration["Authentication:Cognito:SaveToken"]);
                        options.UseTokenLifetime = true;
                        options.Events = new OpenIdConnectEvents
                        {
                            OnTokenValidated = async context =>
                            {
                                var authService = context.HttpContext.RequestServices
                                    .GetRequiredService<IUserAuthenticationService>();
                                await authService.OnTokenValidated(context,
                                    Configuration["Authentication:Cognito:SignedOutRedirectUri"]);
                            },
                            OnRedirectToIdentityProvider = async context =>
                            {
                                var authService = context.HttpContext.RequestServices
                                    .GetRequiredService<IUserAuthenticationService>();
                                await authService.OnRedirectToIdentityProvider(context,
                                    Configuration["Authentication:Cognito:ClientId"]);
                            },
                            OnRedirectToIdentityProviderForSignOut = context =>
                            {
                                var logoutUri =
                                    HttpUtility.UrlEncode(Configuration["Authentication:Cognito:SignedOutRedirectUri"]);
                                var issuerAddress =
                                    $"{Configuration["Authentication:Cognito:LogoutEndpoint"]}/logout?logout_uri={logoutUri}";
                                var authService = context.HttpContext.RequestServices
                                    .GetRequiredService<IUserAuthenticationService>();
    Omar Himada
    @omarhimada
    which one is line 306
    Fagro Vizcaino
    @fagro-vizcaino
    @omarhimada :
      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ConfigSettings config)
            {
    
                var localizationOptions = new RequestLocalizationOptions
                {
                    SupportedCultures = new List<CultureInfo> { new CultureInfo("en-US") },
                    SupportedUICultures = new List<CultureInfo> { new CultureInfo("en-US") },
                    DefaultRequestCulture = new RequestCulture("en-US")
                };
    
                app.UseRequestLocalization(localizationOptions);
                if (env.IsDevelopment() && config.EnableDevelopmentExceptions)
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Error");
                }
    
                app.Use(async (context, next) =>
                {
                    if (context.Request.Path.Value.Contains("invalid"))
                        throw new Exception("ERROR"); <---------------------------------------------------Line 306
    
                    context.Request.Scheme = "https";
                    //if (!env.IsDevelopment())
                    //{
                    //    context.Request.Scheme = "https";
                    //}
                    await next();
                });
                app.UseCookiePolicy();
                app.UseAuthentication();
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "federated",
                        template: "SignIn/{lookupName}",
                        defaults: new { controller = "Account", action = "Auth" });
                    routes.MapRoute("Default", "{controller=Home}/{action=Index}");
                });
    
                app.UseFileServer();
            }
    Omar Himada
    @omarhimada
    you have app.UseAuthentication()
    do you also need app.UseAuthorization()?
    Fagro Vizcaino
    @fagro-vizcaino
    Not so sure. Why ?
    Omar Himada
    @omarhimada
    try useauthorization before useauth
    see if exception persists shrug
    its just that your stacktrace talks about session and i dont normally see use authentication without authorization. just a hunch really
    Fagro Vizcaino
    @fagro-vizcaino
    umm you mean:
     app.UseCookiePolicy();
      app.UseAuthorization();  <-----
      app.UseAuthentication();
    Omar Himada
    @omarhimada
    ya give it a shot
    im not really sure what youre doing with that app.Use(async ... but if that doesnt work i think the problem is in there for sure
    Fagro Vizcaino
    @fagro-vizcaino
    Well, cannot use UseAuthorization because is just available for asp.net 3.0 upward
    i'm on asp.net core 2.1
    Omar Himada
    @omarhimada
    hm
    i mean its definitely being thrown from within that app.Use(async...
    i would debug and see what you can find inside there
    Fagro Vizcaino
    @fagro-vizcaino
    But what about the Correlation failed error ?
    Omar Himada
    @omarhimada
    what happens if instead of throwing a new exception there you do something else
    maybe it has something to do with throwing a new Exception() from within that context
    urothis
    @urothis
    Hey everyone, was looking for some assistance or some good example repos to take a look at, I'm implementing https://docs.aws.amazon.com/iot/latest/developerguide/provision-wo-cert.html I'm at step To initialize the device for use. I'm having a hard time determining which cert I'm supposed to be passing and if I need to generate a csr.
    Fagro Vizcaino
    @fagro-vizcaino
    @omarhimada I end up putting this :
    options.Events = new OpenIdConnectEvents
                            {
                                OnRemoteFailure = context =>
                                {
                                    if (context.Failure.Message.Contains("Correlation failed"))
                                        context.Response.Redirect("/");
                                    else
                                        throw new Exception("ERROR");
    
                                    context.HandleResponse();
    
                                    return Task.CompletedTask;
                                },
                           }
    Omar Himada
    @omarhimada
    did that work?
    Fagro Vizcaino
    @fagro-vizcaino
    yes
    Omar Himada
    @omarhimada
    cool man
    Fagro Vizcaino
    @fagro-vizcaino

    I'm facing another weird stuff, let me see if you guys point me to the right direction

    This is what I'm trying to accomplish:

    If the user login successfully and completed an operation and then instead of signing out just closes the browser tab. Now let's say that after a period of 10 minutes, the user decides to log in again I want to redirect the user to the login page. Instead of automatically login in and go directly to the homepage (that's the behavior that is currently happening).

    Omar Himada
    @omarhimada
    you want to configure session length
    Fagro Vizcaino
    @fagro-vizcaino
    @omarhimada I did, but it's not working. It clears all cookies after 20 min (with the browser close) but I don't any idea where that configuration is coming from.
    bakhtiyar-ospanov
    @bakhtiyar-ospanov
    Hi guys! Are there any updates on download progress callback for AWS Unity SDK (AmazonS3Client.GetObjectAsync)?
    Stiaan Jacobs
    @stiaanj

    Hello there, I hope someone can help me, I have been searching everywhere without finding a solution that works.

    I am using the AWS sdk in dotnet 3.1 worker service to process and upload files to MinIO. Smaller uploads work correctly using the low-level API, but as soon as uploads go over 25mb or so, the uploads get stuck at 100% on the CompleteMultipartUploadAsync. It eventually times out and then fails to complete the upload.

    Can someone push me in the right direction?

    Raymond Sanchez
    @agileraymond
    @stiaanj When you upload a 25mb or bigger, how many parts are you using to upload it?
    Stiaan Jacobs
    @stiaanj
    Its set to use 5mb chunks, 5 parts
    Brad Wight
    @bwarfson
    Hello there, is anyone using an AWS Serverless Application (.Net Core 3.1) with RDS for SQL Server? We are using ADO.net and the repository pattern. If so, what are some best practices for connection pooling? I've been searching and searching but not finding specific examples for AWS Serverless with RDS SQL Server. I've read up on RDS proxy but i guess that doesn't work with SQL Server.
    Omar Himada
    @omarhimada
    have you tried Dapper?
    if ever i cannot use entity framework dapper is right there to save the day
    Jeff Hotchkiss
    @hotchkj
    Hi, is there a way to have S3 uploads resume using the NET Transfer Utility? For example, there's an interruption uploading 20 parts to an object or signed URL, 10 parts are already present in S3, can we resume such that only the remaining 10 parts need to be uploaded? If not, is this something we could consider raising an issue & potential PR for?
    Oscar Andersson
    @NiceGuyAndersson
    Since there's no LoadTableAsync() in the .NetStandard2.0 binaries of DynamoDB, is it impossible to use the Document model in Unity with those binaries?
    Oscar Andersson
    @NiceGuyAndersson
    Actually, I suppose I could convert all my Documents to AttributeMaps and use the non-document functions for network calls
    ellismichaelarb
    @ellismichaelarb
    Hi, I'm having a hard time finding a working example for my scenario, so if anyone can point me in the right direction, I would appreciate it. I'm coming from IdentityServer4, so that's what I'm familiar with. Can I connect an ASP.NET Core app running on my own servers to Cognito for Authentication (and Authorization via Groups)? If so, when my app hits a secured method with [Authorize], can I have the user redirected to Cognito and its login prompt at that point, or do I have to present the user with my own login page and handle the authentication programmatically? Thanks!
    Philip Pittle
    @ppittle
    @ellismichaelarb - I haven't tried it myself, but have you tried the ASP.NET Core Identity Provider for Amazon Cognito? Think this should have what you need: https://aws.amazon.com/blogs/developer/introducing-the-asp-net-core-identity-provider-preview-for-amazon-cognito/
    ellismichaelarb
    @ellismichaelarb
    @ppittle Thanks, I am using that library, but that page leaves some important details out (or I'm just thick). This article has helped me and may have the answers. https://chandradev819.wordpress.com/2020/01/18/aws-cognito-service-in-asp-net-core-3-1-application/
    Sho Nagai
    @shoNagai

    First of all, thank you for the great work.
    I am creating an authentication process using Cognito's StartWithCustomAuthAsync, but I am having an issue with the userAttributes email being undefined in the lambda function that is triggered by this execution. Do you have a solution?

    • client side code

      private static IDictionary<string, string> CreateClientMetadata(string username)
            {
                Dictionary<string, string> meta = new Dictionary<string, string>
                {
                    { "USERNAME", username },
                    { "PASSWORD", Random.RandomString(30) },
                    { "name", username }
                };
                return meta;
            }
      
            private static IDictionary<string, string> CreateAuthParameters(string username)
            {
                var authParams = new Dictionary<string, string>
                {
                    { "USERNAME", username },
                    { "PASSWORD", Random.RandomString(30) },
                    { "email", "test@gmail.com" }
                };
                return authParams;
            }
      
            private CognitoUser CreateCognitoUser(string username)
            {
                var provider =
                    new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.APNortheast1);
                var userPool = new CognitoUserPool(Settings.POOL_ID, Settings.CLIENT_ID, provider);
                return new CognitoUser(username, Settings.CLIENT_ID, userPool, provider);
            }
      
            public async Task<string> Signup(string username)
            {
                var user = this.CreateCognitoUser(username);
      
                var authRequest = new InitiateCustomAuthRequest()
                {
                    ClientMetadata = this.CreateClientMetadata(username),
                    AuthParameters = this.CreateAuthParameters(username)
                };
                var authResponse = await user.StartWithCustomAuthAsync(authRequest).ConfigureAwait(false);
            }
    • lambda code

    import { CognitoUserPoolTriggerHandler } from 'aws-lambda';
    
    export const handler: CognitoUserPoolTriggerHandler = async event => {
        if (!event.request.session || !event.request.session.length) {
             event.request.userAttributes.email
        }
    }
    Phillip Haydon
    @phillip-haydon
    This message was deleted
    Omar Himada
    @omarhimada
    hello AWS folks. i've been integrating with Cognito quite a bit and oftentimes in a different medium
    but i've run into an exception lately that i've never seen before
    i've deployed a .NET core application to a windows server (not EC2) and its giving me this error whenever it makes a request