Giter Club home page Giter Club logo

aws-aspnet-cognito-identity-provider's Introduction

.NET on AWS Banner

ASP.NET Core Identity Provider for Amazon Cognito

nuget

ASP.NET Core Identity Provider for Amazon Cognito simplifies using Amazon Cognito as a membership storage solution for building ASP.NET Core web applications using ASP.NET Core Identity.

This library is not compatible with older versions of Identity such as the ones for ASP.NET MVC5 and lower. It only supports ASP.NET Core Identity and targets the .NET Standard 2.0.

The library introduces the following dependencies:

Getting Started

Follow the examples below to see how the library can be integrated into your web application.

This library extends the ASP.NET Core Identity membership system by using Amazon Cognito as a Custom Storage Provider for ASP.NET Identity.

Referencing the library

Simply add the following NuGet dependencies to your ASP.NET Core application:

Adding Amazon Cognito as an Identity Provider

To add Amazon Cognito as an Identity Provider, make the following change to your code:

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // Adds Amazon Cognito as Identity Provider
    services.AddCognitoIdentity();
    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // If not already enabled, you will need to enable ASP.NET Core authentication
    app.UseAuthentication();
    ...
}

Next the user pool and user pool client need to be configured as part of the IConfiguration of the ASP.NET Core application. For a development user pool edit either the appsettings.Development.json file or the projects secrets.json file. Below is an example of the JSON snippet to go into the file.

"AWS": {
    "Region": "<your region id goes here>",
    "UserPoolClientId": "<your user pool client id goes here>",
    "UserPoolClientSecret": "<your user pool client secret goes here>",
    "UserPoolId": "<your user pool id goes here>"
}

Note: If using appsettings.Development.json or some other file in your project structure be careful checking in secrets to source control.

For a production user pool it is recommend to configure the same settings as above either through IConfiguration's environment variable support or with the AWS System Manager's parameter store which can be integrated with IConfiguration using the Amazon.Extensions.Configuration.SystemsManager NuGet package.

Alternatively, instead of relying on a configuration file, you can inject your own instances of IAmazonCognitoIdentityProvider and CognitoUserPool in your Startup.cs file.

public void ConfigureServices(IServiceCollection services)
{
    ...
    // Adds your own instance of Amazon Cognito clients 
    // cognitoIdentityProvider and cognitoUserPool are variables you would have instanciated yourself
    services.AddSingleton<IAmazonCognitoIdentityProvider>(cognitoIdentityProvider);
    services.AddSingleton<CognitoUserPool>(cognitoUserPool);

    // Adds Amazon Cognito as Identity Provider
    services.AddCognitoIdentity();
    ...
}

Using the CognitoUser class as your web application user class

Once Amazon Cognito is added as the default ASP.NET Core Identity Provider, you need to use the newly introduced CognitoUser class instead of the default ApplicationUser class.

These changes will be required in existing Razor views and controllers. Here is an example with a Razor view:

@using Microsoft.AspNetCore.Identity
@using Amazon.Extensions.CognitoAuthentication

@inject SignInManager<CognitoUser> SignInManager
@inject UserManager<CognitoUser> UserManager

In addition, this library introduces two child classes of SigninManager and UserManager designed for Amazon Cognito authentication and user management workflow: CognitoSigninManager and CognitoUserManager classes.

These two classes expose additional methods designed to support Amazon Cognito features, such as sending validation data to pre-signup AWS Lambda triggers when registering a new user:

/// <summary>
/// Creates the specified <paramref name="user"/> in Cognito with the given password and validation data,
/// as an asynchronous operation.
/// </summary>
/// <param name="user">The user to create.</param>
/// <param name="password">The password for the user</param>
/// <param name="validationData">The validation data to be sent to the pre sign-up lambda triggers.</param>
/// <returns>
/// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/>
/// of the operation.
/// </returns>
public async Task<IdentityResult> CreateAsync(TUser user, string password, IDictionary<string, string> validationData)

Explore the documentation and sample application

Feel free to explore the documentation folder and the sample application. These two resources provide additionnal examples on how to use the library with your ASP.NET Core web application.

Getting Help

We use the GitHub issues for tracking bugs and feature requests and have limited bandwidth to address them.

If you think you may have found a bug, please open an issue

Contributing

We welcome community contributions and pull requests. See CONTRIBUTING for information on how to set up a development environment and submit code.

Additional Resources

AWS .NET GitHub Home Page
GitHub home for .NET development on AWS. You'll find libraries, tools, and resources to help you build .NET applications and services on AWS.

AWS Developer Center - Explore .NET on AWS
Find all the .NET code samples, step-by-step guides, videos, blog content, tools, and information about live events that you need in one place.

AWS Developer Blog - .NET
Come see what .NET developers at AWS are up to! Learn about new .NET software announcements, guides, and how-to's.

@dotnetonaws
Follow us on twitter!

License

Libraries in this repository are licensed under the Apache 2.0 License.

See LICENSE and NOTICE for more information.

aws-aspnet-cognito-identity-provider's People

Contributors

96malhar avatar alexisatkinson avatar ashishdhingra avatar ashovlin avatar camiledahdah avatar costleya avatar ganeshnj avatar hyandell avatar jherbert avatar joshongithub avatar kellertk avatar klaytaybai avatar ngl321 avatar normj avatar phoniccanine avatar somayab avatar srutig avatar sstevenkang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aws-aspnet-cognito-identity-provider's Issues

Issue with confirming email change of the user (edge case flow issue)

Ok, so you changed in 0.9.0.8 worked for me in terms of allowing me to retrieve a user with session tokens properly so I could confirm an email and phone number changed. I found an edge case that is a catch 22 when changing the email address. Keep in mind, my user pool is configured for the email address as the username.

If I change the email address to another email, I can then verify it immediately AS LONG as I stayed logged in. However, if I change the email address to a different address, then close the browser or log out BEFORE I confirm it, then return and login with the NEW email address, it wont let me log in because the email address is not confirmed. When I try to log in, I receive a response of:

result.IsNotAllowed = true

So I figured, ok, let me just redirect to my confirmation page and allow the user to resend a new code or input the original if they have it, however, I am not considered logged in as the CognitoUser does not contain session tokens. So I tried to so a simple SigninAsync, but the user it returns has no session tokens and if I try to do a FindByXXX after a Signin Async, I still get a user with no session tokens, probably due to the fact I have not confirmed the email. So if this happens the user account is dead in the water is at cant login to confirm the email because its not confirmed and I cant resend a confirmation as the user is not logged in.

Its almost as if you need to do what you did for the account confirmation:

ResendSignupConfirmationCodeAsync

So I can resend an email confirmation code if Im not logged in as Im not sending it until the user actually puts in a valid name and password and cognito tells me the user email is not verified, at that point I know I have a valid user. Thoughts?

How do i get current user from home controller?

Title says it all. I can't figure out how to get the current user from my home controller.

I have a 2nd question, I can create a new post for it, but I figured it'd try it here. Is there any existing framework for a user deleting their account? Or do I have to write it myself with UserManager.DeleteAsync(); Just asking so I dont waste anymore time looking for it.

Thanks!

Result from PasswordSignInAsync does not contain an ERRORS property when it fails.

Int he case of many of the calls, when there is a failure, an ERRORS property is available for me to loop through and get the errors. In the case of PasswordSignInAsync, when it fails (where SUCCEEDED = false). I cant tell why it failed. there are several properties like ISLOCKEDOUT, PASSWORDRESETREQUIRED, but if the failure is not due to any of those errors, I cant trap what caused it.

For instance, I tried to login with a user email that doesnt exist or one that does exist with the incorrect password and I cant tell which is which. I also cant tell if too many attempts were made. Is this by design. Im thinking I can just show them a generic error but I would like to log on my end that someone is attempting to login incorrectly too many times.

AddCognitoIdentity raises StackOverflow exception

AddCognitoIdentity is throwing StackOverflow exception. It was working fine but now it keeps throwing the exception as soon as an application is launched.

System.StackOverflowException in System.Private.CoreLib.lib

If you need a sample code to investigate feel free to use this code (.net core 3 preview with VS 2019 preview)

Sample Asp.net core

Cannot Resolve CognitoSignInManager

I have followed the documentation and I have read the sample code(s) multiple times however when I try to create a user I get this error:

InvalidOperationException: Unable to resolve service for type 'Amazon.AspNetCore.Identity.Cognito.CognitoSignInManager`

What I have done is to use:

services.AddCognitoIdentity();

as well as

app.UseAuthentication();

But seems that AddCognitoIdentity() does not inject CognitoSignInManager and CogniroUserManager

p.s. I have created the "AWS" entry in appsettings.json file so no issue there.

Update:

I added these two lines of code to ConfigureServices and that fixed the problem:

services.AddTransient<CognitoSignInManager>();
services.AddTransient<CognitoUserManager>();

Sample results in 'The hostname could not be parsed'

Perhaps there are some extra configuration steps I need to do. I've cloned the repository and added the aws settings to appsettings.json but I get the following error when running in visual studio:

UriFormatException: Invalid URI: The hostname could not be parsed. System.Uri.CreateThis(string uri, bool dontEscape, UriKind uriKind) Amazon.Runtime.ClientConfig.GetUrl(RegionEndpoint regionEndpoint, string regionEndpointServiceName, bool useHttp, bool useDualStack) in ClientConfig.cs Amazon.Runtime.ClientConfig.DetermineServiceURL() in ClientConfig.cs Amazon.Runtime.Internal.DefaultRetryPolicy..ctor(IClientConfig config) in DefaultRetryPolicy.cs Amazon.Runtime.AmazonServiceClient.BuildRuntimePipeline() in AmazonServiceClient.cs

I also tried following the instructions here https://aws.amazon.com/blogs/developer/introducing-the-asp-net-core-identity-provider-preview-for-amazon-cognito/ to the point where my site was complaining about no login page when run. I notice the sample has a Identity Area with the pages in. I'm not sure why the post does not explain whatever extra steps need to be done to add these.

Looking forward to getting this integrated.

Confirming Phone number throws an an error

When I attempt to confirm a phone number change with a verification code using

await _userManager.ConfirmPhoneNumberAsync(user, code)

I receive the following error:

NullReferenceException: Object reference not set to an instance of an object.
Amazon.AspNetCore.Identity.Cognito.CognitoUserStore<TUser>.VerifyUserAttributeAsync(TUser user, string attributeName, string code, CancellationToken cancellationToken)
Client.WebApp.Controllers.AccountController.Confirm(Confirm model) in AccountController.cs
+
                        result = await _userManager.ConfirmPhoneNumberAsync(user, model.Code).ConfigureAwait(false);
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
NToastNotify.NtoastNotifyAjaxToastsMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass5_1+<<UseMiddlewareInterface>b__1>d.MoveNext()
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

The user manager, user and code are all valid and it appears its blowing up trying to verify the phone attribute, but that exists too in my user below:

image

Set identity expiration/timeout

Hi there,

I'm trying to set the identity expiration for my users but it doesn't seem to be working. I've set it to a two hour sliding expiration but I seem to get automatically logged out after about 30 minutes or so. Could you advise? Here is what I have currently:

services.AddCognitoIdentity();
services.AddSingleton<IAmazonCognitoIdentityProvider>(cognitoClient);
services.AddSingleton<CognitoUserPool>(userPool);

services
	.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
	.AddCookie();

services
	.ConfigureApplicationCookie(o =>
	{
		o.ExpireTimeSpan = TimeSpan.FromHours(2);
		o.SlidingExpiration = true;
		o.LoginPath = "/Identity/Account/Login";
		o.LogoutPath = "/Identity/Account/Logout";
	});

Resetting the user password when the user is authenticated and has session tokens

So I have a user profile page and the user is authenticated with a full session. I have a section to offer a password reset, but the only option I can see for resetting the password is one that requires a code, which I thought was only necessary if the user is not authenticated.

In the Node.js Amplify version I wrote, I can change the user's password if they are authenticated and not require a verification code.

Is there a way to not make the user have to switch screens and enter an authenitcation code? I implemented it with that process and it works, just seems like overkill if the user changing the password is authenticated, unlike when you do a forgot password and then utilize the resetpasswordasync.

I tried the RemovePassword and AddPassword and that threw errors it was not implemented.

How to work with ApplicationDbContext

According to this blog we have to remove all references of ApplicationDbContext
in Startup.cs to work with Cognito provider.

image

But i need ApplicationDbContext to instance to query data in my local database.
I have a question that how we can inject ApplicationDbContext to ServiceCollection?
Please give an example.
Thanks!

[Authorize(Roles = "<Role>")] doesn't work

It would be nice to do role based authorization via [Authorize(Roles= "{Role}")]; however currently it doesn't work; in part probably because cognito (groups/roles) are mapped to cognito:groups.

p.s. it's one of the examples on the announcement page, so seems like it ought to work: https://aws.amazon.com/blogs/developer/now-generally-available-the-asp-net-core-identity-provider-for-amazon-cognito/

Is there a way to get it to work?
p.s. besides writing custom policy

p.s. also posted this question on https://stackoverflow.com/questions/55234563/role-based-authorization-for-aws-cognito

Issues with SignUpAsync when Cognito is configured for username as the email address

So after some extensive use of this package for the last few days, I have noticed that when you setup Cognito to use the email address as the username as shown below:

image

I started to have a few issues, one I was able to get around, the other I cannot and am stuck. In your sample, in the Register.cshtml.cs file, first thing, you have to change is the Cognito user creation to use the Email address instead of the username (which is what I would have expected):

CognitoUser user = _pool.GetUser(Input.Email);

However, when the next piece of code runs:

IdentityResult result = await _userManager.CreateAsync(user, Input.Password).ConfigureAwait(false);
if (result.Succeeded)
{
    _logger.LogInformation("User created a new account with password."); 
    await _signInManager.SignInAsync(user, false).ConfigureAwait(false);
    return RedirectToPage("./ConfirmAccount");
}

This piece of code fails with a USER NOT FOUND error:

await _signInManager.SignInAsync(user, false).ConfigureAwait(false);

It fails because the "user" variable that was created at the beginning has a userid = the email address, which is NOT how cognito stores it. When the user is created in Cognito uising this configuration, the userid is replaced with a randomly generated GUID/UUID as shown below:

image

The current Cognito "user" variable is not updated or passed back after the CreateAsync is called. Once I figured this out I inserted an additional line in the above code to refresh the user by looking them up by their email address

user = await _userManager.FindByEmailAsync(Input.Email).ConfigureAwait(false);

Once I did that, THEN I could see that the username/userid in the newly retrieved "user" variable contained the GUID/UUID. Successively, the SignInAsync call worked and after that the Confirm also worked. So I was able to work around that issue, however, I have to make and additional call to get proper user with the proper ID in the Cognito user object.

Now I go to logout and in the samples LogOut.cshtml.cs page code, it's a simple call:

await _signInManager.SignOutAsync().ConfigureAwait(false);

When that call is made it throws an error trying to find the current user to log them out and of course the "username" field is incorrect as its not getting what it needs:

InvalidParameterException: 1 validation error detected: Value at 'username' failed to satisfy constraint: Member must satisfy regular expression pattern: [\p{L}\p{M}\p{S}\p{N}\p{P}]+

CognitoServiceException: Failed to find the Cognito User by Id

Somehow this needs to be adjusted to account for this email as the username/userid structure or, it has to let me pass a Cognito user with the proper id as an overload. Right now Im dead in the water because I cant log my user out. I tried to get the Cognito user and then perform a GlobalSignOut with the following code:

string userId = User.Claims.FirstOrDefault().Value;
CognitoUser user = await _userManager.FindByIdAsync(userId).ConfigureAwait(false);
await user.GlobalSignOutAsync().ConfigureAwait(false);

It retrieves the correct user with the correct GUID/UUID, but this also failed with an error that the user is not authenticated?!?! Not sure how that can be when the SignInAsyc from the Login page is successful.

NotAuthorizedException: User is not authenticated.
Amazon.Extensions.CognitoAuthentication.CognitoUser.EnsureUserAuthenticated()
Amazon.Extensions.CognitoAuthentication.CognitoUser.GlobalSignOutAsync()
Samples.Areas.Identity.Pages.Account.LogoutModel.OnPost(string returnUrl) in Logout.cshtml.cs
+
await user.GlobalSignOutAsync().ConfigureAwait(false);
Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory+GenericTaskHandlerMethod.Convert<T>(object taskAsObject)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory+GenericTaskHandlerMethod.Execute(object receiver, object[] arguments)
Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeHandlerMethodAsync()

Getting System.Net.Sockets.SocketException while running samples

I'm receiving "System.Net.Sockets.SocketException: A socket operation was attempted to an unreachable network" exception running Samples project.
I've updated appsettings with my User Pool values, and trying to login/register.

System.Net.Http.HttpRequestException: A socket operation was attempted to an unreachable network ---> System.Net.Sockets.SocketException: A socket operation was attempted to an unreachable network
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
at System.Threading.Tasks.ValueTask1.get_Result() at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) at System.Threading.Tasks.ValueTask1.get_Result()
at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask1 creationTask) at System.Threading.Tasks.ValueTask1.get_Result()
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.DiagnosticsHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts) at System.Net.Http.HttpClient.GetStringAsyncCore(Task1 getTask)
at Amazon.Runtime.Internal.Util.AsyncHelpers.<>c__DisplayClass1_11.<<RunSync>b__0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Amazon.Runtime.Internal.Util.AsyncHelpers.ExclusiveSynchronizationContext.BeginMessageLoop() in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Internal\Util\_mobile\AsyncHelpers.cs:line 142 at Amazon.Runtime.Internal.Util.AsyncHelpers.RunSync[T](Func1 task) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Internal\Util_mobile\AsyncHelpers.cs:line 87
at Amazon.Util.AWSSDKUtils.DownloadStringContent(Uri uri, TimeSpan timeout, IWebProxy proxy) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Util\AWSSDKUtils.cs:line 1000
at Amazon.Util.EC2InstanceMetadata.GetItems(String relativeOrAbsolutePath, Int32 tries, Boolean slurp) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Util_bcl+coreclr\EC2InstanceMetadata.cs:line 513
at Amazon.Util.EC2InstanceMetadata.get_IAMSecurityCredentials() in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Util_bcl+coreclr\EC2InstanceMetadata.cs:line 311
at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.FetchCredentials() in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials_bcl+coreclr\DefaultInstanceProfileAWSCredentials.cs:line 142
at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.GetCredentials() in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials_bcl+coreclr\DefaultInstanceProfileAWSCredentials.cs:line 88
at Amazon.Runtime.DefaultInstanceProfileAWSCredentials.GetCredentialsAsync() in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Credentials_bcl+coreclr\DefaultInstanceProfileAWSCredentials.cs:line 106
at Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\Handlers\CredentialsRetriever.cs:line 90
at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\RetryHandler\RetryHandler.cs:line 137
at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Extensions.CognitoAuthentication.CognitoUserPool.FindByIdAsync(String userID)
at Amazon.AspNetCore.Identity.Cognito.CognitoUserStore1.FindByIdAsync(String userId, CancellationToken cancellationToken) at Amazon.AspNetCore.Identity.Cognito.CognitoSignInManager1.PasswordSignInAsync(String userId, String password, Boolean isPersistent, Boolean lockoutOnFailure)
at Samples.Areas.Identity.Pages.Account.LoginModel.OnPostAsync(String returnUrl) in C:\Users\vadim.burshtyn\Desktop\aws-aspnet-cognito-identity-provider-master\aws-aspnet-cognito-identity-provider-master\samples\Samples\Areas\Identity\Pages\Account\Login.cshtml.cs:line 74
at Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.GenericTaskHandlerMethod.Convert[T](Object taskAsObject)
at Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.GenericTaskHandlerMethod.Execute(Object receiver, Object[] arguments)
at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeHandlerMethodAsync()
at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeNextPageFilterAsync()
at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Any help with this?
Thanks in advance.

Populate session tokens

Is there any attributes which would return an access token or Id Token for client-side authentication?

Password policy is ignored by SDK

If I create a User Pool in Cognito and set a loose password policy, then when I sign up a user with a simple password such as 123456, I will get an exception about the password not following the set policy.

However when AddCognitoIdentity is added with options which set the policy, the user can be created with a simple password.

Since the Cognito service is the decider of the password policy the SDK must fetch the policy from Cognito and user that rather than having some defaults.

Updating user attributes

So in looking at everything, I'm not easily seeing how to update CognitoUser attributes. I see I can set can call CognitoUser.Attributes[<attributename>] and set it, but how do I push it to Cognito?

I tried CognitoUser.UpdateAttributesAsync after updating the attributes and it throws an error below that the user is not authenticated, yet I know they are as I just logged in. I know Im close, what am I doing wrong?

NotAuthorizedException: User is not authenticated.
Amazon.Extensions.CognitoAuthentication.CognitoUser.EnsureUserAuthenticated()
Amazon.Extensions.CognitoAuthentication.CognitoUser.CreateUpdateUserAttributesRequest(IDictionary<string, string> attributes)
Amazon.Extensions.CognitoAuthentication.CognitoUser.UpdateAttributesAsync(IDictionary<string, string> attributes)
Wamba.Client.WebApp.Controllers.ProfileController.Index(Index model) in ProfileController.cs
+
               await user.UpdateAttributesAsync(user.Attributes).ConfigureAwait(false);
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
NToastNotify.NtoastNotifyAjaxToastsMiddleware.InvokeAsync(HttpContext context, RequestDelegate next)
Microsoft.AspNetCore.Builder.UseMiddlewareExtensions+<>c__DisplayClass5_1+<<UseMiddlewareInterface>b__1>d.MoveNext()
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

How do I resend a registration confirmation email

So if I register a new user and for some reason fail to confirm the signup. When I try to login later it fails with NOTALLOWED = TRUE, which means the email/account is not verified. Keep in mind I am using the email as the username for login. Is there a way to resend the confirmation code email? I cant seem to find anything. When I try to run

await _userManager.SendEmailConfirmationTokenAsync(<CognitoUser>)

It fails with an OBJECT NOT SET TO INSTANCE OF REFERENCE and I am retrieving and passing a valid user. I do do a down and dirty way of just changing the EMAIL attribute to the same email but Im not sure that forces a new email confirmation code to be sent. This is important as I have the flag set to not allow the user to login if the email is not confirmed, so I need to be able to let the user choose to resend one if they didnt get it or they didnt see it.

Null Exception Error for UserManager FindBy* methods

var user = await _userManagerFindByName(username);

generates the null exception error below

{System.NullReferenceException: Object reference not set to an instance of an object.
   at Amazon.AspNetCore.Identity.Cognito.CognitoUserManager`1.PopulateTokens(TUser user, String claimType, String claimValue)

The User Pool is set to allow sign in by username and verified email. However, everything else that I've tested seems to work. GetUsersAsync() works, CreateUser, AddToRoleAsync, getting tokens... all work.

StackOverflowException during authentication process

Hello,

It should be related to #33. I'm using ASP.NET Core 2.1.

After a while after login, when I attempted to open a site again, StackOverflowException happens at AuthenticateAsync() in the following method:

        public override async Task SignOutAsync()
        {
            // Retrieve the current signed in CognitoUser and log him out first
            var result = await Context.AuthenticateAsync(IdentityConstants.ApplicationScheme).ConfigureAwait(false);

Presumably SignOutAsync() was called during authentication process. AuthenticateAsync() in this method invokes SignOutAsync() again, then it enters infinite loop, eventually StackOverflowException was thrown.

My main problem is a failure of authentication. Surely cookie causes the error, as I could be resumed from the error by deleting the cookie.
I couldn't point out which module causes the error, aws-aspnet-cognito-identity-provider or aws-sdk-net-extensions-cognito though.

Trying to get tokens and Current User

Im creating an .net core MVC POC app using Visual Studio for Mac.

I'm able to sign in successfully however I'm not able to get the access token for the current user. I'm also not able to get the current user.

public class AccountController : Controller
{
    private readonly SignInManager<CognitoUser> _signInManager;
    private readonly ILogger<AccountController> _logger;
    private readonly CognitoUserPool _cognitoPool;
    public AccountController(SignInManager<CognitoUser> signInManager, ILogger<AccountController> logger, CognitoUserPool cognitoPool)
    {
        _signInManager = signInManager;
        _logger = logger;
        _cognitoPool = cognitoPool;
    }

    [HttpPost]
    public async Task<IActionResult> Login(Models.LoginModel login, string returnUrl)
    {
        returnUrl = returnUrl ?? Url.Content("~/");

        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(login.UserName, login.Password, login.RememberMe, lockoutOnFailure: false);
            if (result.Succeeded)
            {
                _logger.LogInformation("User logged in.");

                var token = await _signInManager.Context.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
                var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);

                var user = _cognitoPool.GetUser();
                var user2 = _signInManager.Context.User;

                var tokens = user.SessionTokens;
                var claims = user2.Claims;


                return LocalRedirect(returnUrl);
            }

            ModelState.AddModelError(string.Empty, "Invalid login attempt.");
            return View();
        }

        // If we got this far, something failed, redisplay form
        return View();
    }
}

token, accessToken, tokens are all null and claims are empty. I'm not sure what I'm missing.

Final question, I couldn't get the app to work without an AWS Profile in app.settings and having an IAM user with the AmazonCognitoReadOnly policy. I didn't see that in the documentation but it failed without it. I may have set this up wrong. Any help would be appreciated.

Is MultiFactor Authentication working in this library yet?

Ive been able to implement MFA in the node.js world with Amplify but in switching over to the .NET Core2 world and this library, Im finding a lot of the base calls surrounding MFA or 2FA are not implemented. I need to do SMS and TOTP. In the node.js world using Amplify I can simply use setPreferredMFA (none, SMS or TOTP) and VerifyTotpToken. Then when its MFA I run setupTOTP, which generates 32 digit code that I can use to format for the Google Authenticator.

Can you get me started in the correct direction on what to call here (if it is fully implemented)?

Change email flow with verification turned off

The user registration flow for my application is as follows:

  1. User registers (UserManager.CreateAsync())
  2. Upon completing the registration for, the user is presented with a message saying that their account needs to be approved before they can log in.
  3. An admin will approve their account (currently setting a custom 'approved' attribute to 1) which will change the status of the user to CONFIRMED. Currently I'm just doing this in the Cognito console.
  4. User can then log in
  5. User can go to a 'manage account' page and change their email if they want (email changed with call to UserManager.SetEmailAsync()).

I have disabled verification in Cognito for my user pool:
image

I have done this because I don't want the emails to be sent immediately after the user registers, I do actually want them to verify their email but not until the admin approval has taken place. I can't see a way to manually send the email with the .NET Identity API (can you confirm?) so I intend to build my own email system for this at a later time.

The problem I'm having is if the user decides to change their email, and then logs out and tries to log back in with their new email, I get a UserNotConfirmedException. I've checked the status of the user in Cognito and it's still CONFIRMED so I'm not really sure what the correct process is here.

I've also tried adding an extra call to AdminConfirmSignUpAsync() after the user changes their email but I just get an exception saying the user is already CONFIRMED which I guess is expected. However, the user is now in a state where it IS confirmed but can't log in and verification is disabled.

I understand this may not be within the scope of this project and may be an underlying issue but I figured I'd get your input first!

Changing the phone number in the Identity scaffolded pages throws KeyNotFoundException: The given key 'phone_number' was not present in the dictionary error

So I went ahead and scaffolded in the Identity pages for managing the user profile (Account/Manage/Index an corresponding management layout files). I switched out all the injections to accommodate the Cognito User Manager and Sign in Manager object. When I try to open the Index page as the user's profile, it throws the following error:

KeyNotFoundException: The given key 'phone_number' was not present in the dictionary.

When the following line of code is run:

var phoneNumber = await _userManager.GetPhoneNumberAsync(user).ConfigureAwait(false);

and Im assuming that it also throws an error when you run this one also:

var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber).ConfigureAwait(false);

The same calls for the email work just fine (GetEmailAsync and SetEmailAsync). I figured these were just missed, but I will need them to function as I will be using SMS as well. I could go the route of updating the attributes instead, but this makes life a lot easier.

Thanks for looking into this and hopefully Im not missing something.

Empty Read and Write attributes list should assume all attributes are readable and writable

Currently, the code to get a user's attribute that's used in places such as UserManager.IsEmailConfirmedAsync checks the user pool client configuration to see if the client has permissions to read that attribute.

But the code goes against what Cognito says:

All attributes are readable and writable by default because none are selected.

Would it be possible to make a change to the implementation to guarantee the same thing?

How do I retrieve the Access Token from the UserManager?

I need to pass the Access token to my API Lambda functions and I Im kind of scratching my head on how to get it once logged in. I see there is a function called:

GetAuthenticationTokenAsync

but when I try to use it I get a NotSupportedException.

SignInManager.PasswordSignInAsync Throws OperationCanceledException. Timing out?

Hello,

I'm integrating Cognito into Piranha CMS (Source: https://github.com/PiranhaCMS/piranha.core), and I get an OperationCanceledException, while using this:

public async Task<bool> SignIn(object context, string username, string password)
        {
            if (_seed != null)
            {
                await _seed.CreateAsync();
            }

            SignInResult result = null;

            result = await _signInManager.PasswordSignInAsync(username, password, true, false)
                .ConfigureAwait(false); // OperationCanceledException. I'm guessing that indicates a timeout, but not positive.

            return result?.Succeeded == true;
        }

I'm not positive if it is related to the CMS, but I see nothing in their source or anything else that would cause that exception, so I posted this on your end to see what you think. The sign in line throws,

Full Code of ISecurity:

        public class CognitoIdentitySecurity : ISecurity
    {
        /// <summary>
        /// The optional identity seed.
        /// </summary>
        private readonly IIdentitySeed _seed;

        /// <summary>
        /// The sign in manager.
        /// </summary>
        private readonly SignInManager<CognitoUser> _signInManager;

        /// <summary>
        ///     Default constructor.
        /// </summary>
        public CognitoIdentitySecurity(SignInManager<CognitoUser> signInManager, IIdentitySeed seed = null)
        {
            _signInManager = signInManager;
            _seed = seed;
        }

        /// <summary>
        /// Authenticates and signs in the user with the
        /// given credentials.
        /// </summary>
        /// <param name="context">The current application context</param>
        /// <param name="username">The username</param>
        /// <param name="password">The password</param>
        /// <returns>If the user was signed in</returns>
        public async Task<bool> SignIn(object context, string username, string password)
        {
            if (_seed != null)
            {
                await _seed.CreateAsync();
            }

            SignInResult result = null;

            result = await _signInManager.PasswordSignInAsync(username, password, true, false)
                .ConfigureAwait(false);

            return result?.Succeeded == true;
        }

        /// <summary>
        /// Signs out the current user.
        /// </summary>
        /// <param name="context">The current application context</param>
        public Task SignOut(object context)
        {
            return _signInManager.SignOutAsync();
        }
    }
}

Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.AspNetCore.Identity.Cognito;
using Amazon.CognitoIdentityProvider;
using Amazon.Extensions.CognitoAuthentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Piranha;
using Piranha.AspNetCore.Identity;
using Piranha.AspNetCore.Identity.Data;
using Piranha.AspNetCore.Identity.SQLite;
using Piranha.ImageSharp;
using Piranha.Local;
using Piranha.Manager;
using SmoothOdds.Services;

namespace SmoothOdds
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(config =>
            {
                config.ModelBinderProviders.Insert(0, new Piranha.Manager.Binders.AbstractModelBinderProvider());
            });
            services.AddCognitoIdentity();
            //services.AddTransient<CognitoSignInManager<CognitoUser>>();
            services.AddTransient<ISecurity, CognitoIdentitySecurity>();
            //services.AddTransient<UserManager<CognitoUser>>();

            services.AddPiranhaApplication();
            services.AddPiranhaFileStorage();
            services.AddPiranhaImageSharp();
            services.AddPiranhaEF(options => options.UseSqlite("Filename=./piranha.db"));
            services.AddPiranhaManager();
            services.AddPiranhaMemCache();

            // Setup authorization policies
            services.AddAuthorization(o =>
            {
                // Role policies
                o.AddPolicy(Permissions.Roles, policy =>
                    {
                        policy.RequireClaim(Permission.Admin, Permission.Admin);
                        policy.RequireClaim(Permissions.Roles, Permissions.Roles);
                    });
                o.AddPolicy(Permissions.RolesAdd, policy =>
                {
                    policy.RequireClaim(Permission.Admin, Permission.Admin);
                    policy.RequireClaim(Permissions.Roles, Permissions.Roles);
                    policy.RequireClaim(Permissions.RolesAdd, Permissions.RolesAdd);
                });
                o.AddPolicy(Permissions.RolesDelete, policy =>
                {
                    policy.RequireClaim(Permission.Admin, Permission.Admin);
                    policy.RequireClaim(Permissions.Roles, Permissions.Roles);
                    policy.RequireClaim(Permissions.RolesDelete, Permissions.RolesDelete);
                });
                o.AddPolicy(Permissions.RolesEdit, policy =>
                {
                    policy.RequireClaim(Permission.Admin, Permission.Admin);
                    policy.RequireClaim(Permissions.Roles, Permissions.Roles);
                    policy.RequireClaim(Permissions.RolesEdit, Permissions.RolesEdit);
                });
                o.AddPolicy(Permissions.RolesSave, policy =>
                {
                    policy.RequireClaim(Permission.Admin, Permission.Admin);
                    policy.RequireClaim(Permissions.Roles, Permissions.Roles);
                    policy.RequireClaim(Permissions.RolesSave, Permissions.RolesSave);
                });

                // User policies
                o.AddPolicy(Permissions.Users, policy =>
                    {
                        policy.RequireClaim(Permission.Admin, Permission.Admin);
                        policy.RequireClaim(Permissions.Users, Permissions.Users);
                    });
                o.AddPolicy(Permissions.UsersAdd, policy =>
                {
                    policy.RequireClaim(Permission.Admin, Permission.Admin);
                    policy.RequireClaim(Permissions.Users, Permissions.Users);
                    policy.RequireClaim(Permissions.UsersAdd, Permissions.UsersAdd);
                });
                o.AddPolicy(Permissions.UsersDelete, policy =>
                {
                    policy.RequireClaim(Permission.Admin, Permission.Admin);
                    policy.RequireClaim(Permissions.Users, Permissions.Users);
                    policy.RequireClaim(Permissions.UsersDelete, Permissions.UsersDelete);
                });
                o.AddPolicy(Permissions.UsersEdit, policy =>
                {
                    policy.RequireClaim(Permission.Admin, Permission.Admin);
                    policy.RequireClaim(Permissions.Users, Permissions.Users);
                    policy.RequireClaim(Permissions.UsersEdit, Permissions.UsersEdit);
                });
                o.AddPolicy(Permissions.UsersSave, policy =>
                {
                    policy.RequireClaim(Permission.Admin, Permission.Admin);
                    policy.RequireClaim(Permissions.Users, Permissions.Users);
                    policy.RequireClaim(Permissions.UsersSave, Permissions.UsersSave);
                });
            });

            return services.BuildServiceProvider();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services, IApi api)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // Initialize Piranha
            App.Init();

            // Configure cache level
            App.CacheLevel = Piranha.Cache.CacheLevel.Basic;

            // Build content types
            var pageTypeBuilder = new Piranha.AttributeBuilder.PageTypeBuilder(api)
                .AddType(typeof(Models.BlogArchive))
                .AddType(typeof(Models.StandardPage))
                .AddType(typeof(Models.StartPage));
            pageTypeBuilder.Build()
                .DeleteOrphans();
            var postTypeBuilder = new Piranha.AttributeBuilder.PostTypeBuilder(api)
                .AddType(typeof(Models.BlogPost));
            postTypeBuilder.Build()
                .DeleteOrphans();

            // Register middleware
            app.UseStaticFiles();
            app.UseAuthentication();
            app.UsePiranha();
            app.UsePiranhaManager();
            app.UseHttpsRedirection();
            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "areaRoute",
                    template: "{area:exists}/{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });

                routes.MapRoute(
                    name: "default",
                    template: "{controller=home}/{action=index}/{id?}");
            });
        }
    }
}

SocketException "Device not configured" when running the sdk on macos

I am trying to do the development on macos and when I try to run the code, I get a SocketException "Device not configured ".

I am wondering if others have encountered this error before.

System.Net.Http.HttpRequestException: Device not configured ---> System.Net.Sockets.SocketException: Device not configured
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.WaitForCreatedConnectionAsync(ValueTask`1 creationTask)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   at Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken) in D:\JenkinsWorkspaces\trebuchet-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\HttpHandler\_mobile\HttpRequestMessageFactory.cs:line 524
   at Amazon.Runtime.Internal.HttpHandler`1.InvokeAsync[T](IExecutionContext executionContext) in D:\JenkinsWorkspaces\trebuchet-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\HttpHandler\HttpHandler.cs:line 175
   at Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.EndpointDiscoveryHandler.InvokeAsync[T](IExecutionContext executionContext) in D:\JenkinsWorkspaces\trebuchet-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\Handlers\EndpointDiscoveryHandler.cs:line 79
   at Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext) in D:\JenkinsWorkspaces\trebuchet-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\Handlers\CredentialsRetriever.cs:line 98
   at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext) in D:\JenkinsWorkspaces\trebuchet-stage-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\RetryHandler\RetryHandler.cs:line 137
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext executionContext)
   at Amazon.Extensions.CognitoAuthentication.CognitoUserPool.FindByIdAsync(String userID)
   at Amazon.AspNetCore.Identity.Cognito.CognitoUserStore`1.FindByIdAsync(String userId, CancellationToken cancellationToken)
   at Amazon.AspNetCore.Identity.Cognito.CognitoUserManager`1.FindByIdAsync(String userId)
   at Amazon.AspNetCore.Identity.Cognito.CognitoSignInManager`1.PasswordSignInAsync(String userId, String password, Boolean isPersistent, Boolean lockoutOnFailure)
   at Samples.Areas.Identity.Pages.Account.LoginModel.OnPostAsync(String returnUrl) in /Users/giskard/buylogic/BuyLogic/BuyLogic/Areas/Identity/Pages/Account/Login.cshtml.cs:line 74
   at Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.GenericTaskHandlerMethod.Convert[T](Object taskAsObject)
   at Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory.GenericTaskHandlerMethod.Execute(Object receiver, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeHandlerMethodAsync()
   at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeNextPageFilterAsync()
   at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
   at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeInnerFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)```

Retrieving userName and sub immediately after registration.

I'm trying to get the user name and the user's sub right after registration, right after " await _signInManager.SignInAsync(user, isPersistent: false);". I can't seem to find the right way to do this.

Also, which is better for storing a unique user identifier in my database, the sub or the user name?

Possible to retrieve user created date?

Me again.

I can see in Cognito that there's a 'Created Date' field but I can't figure out how to get hold of this value programatically. It's not returned in the collection attributes and I can't see a method to get it explicitly. Is it possible?

Manage Group of user pool

Hi guys,

Accordingly this doc I found these sentences.
image

I want to use APIs to manage groups and users of those groups. How can i do that?
Please give me a help! Thanks

Refreshing the Access token

So from my reading and by experience the Access token is good for one hour. After that you need to refresh it with the Refresh token. I know the Amplify node.js library automatically does it.

Does that happen with this library? If not what is the flow or process for checking it and refreshing it and what can I call here to do that. I'm not seeing the ability to do that anywhere (of course I may just be blind). I was hoping that when I do a _userManager.FindByXXXX, that the tokens would be refreshed for me, but the user manager code is not showing that is happening.

Thoughts?

Use multiple user pools

If I wanted to use multiple User Pools in my application what would I do to implement that?

'Missing Authentication Token' when creating user

Hi there,

I'm trying to set us the registration flow for a new website. I have followed the guide for setting up the Identity in Startup.cs and also copied the sample Register page code. You can see both below.

Startup.cs

// Identity
var awsCredentials = new BasicAWSCredentials(this.config["AWS:AccessKey"], this.config["AWS:SecretKey"]);
var cognitoClient = new AmazonCognitoIdentityProviderClient(awsCredentials, RegionEndpoint.EUWest2);
var userPool = new CognitoUserPool(
	config["Cognito:PoolId"],
	config["Cognito:ClientId"],
	cognitoClient,
	config["Cognito:ClientSecret"]);

services.AddCognitoIdentity();
services.AddSingleton<IAmazonCognitoIdentityProvider>(cognitoClient);
services.AddSingleton<CognitoUserPool>(userPool);

services
	.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
	.AddCookie();
	
services
	.ConfigureApplicationCookie(o =>
	{
		o.Cookie.HttpOnly = true;
		o.ExpireTimeSpan = TimeSpan.FromHours(1);
		o.SlidingExpiration = true;
		o.LoginPath = "/Identity/Account/Login";
		o.LogoutPath = "/Identity/Account/Logout";
	});

services
	.Configure<SecurityStampValidatorOptions>(o =>
	{
		o.ValidationInterval = TimeSpan.FromHours(1);
	});

Register.cshtml.cs

using Amazon.AspNetCore.Identity.Cognito;
using Amazon.Extensions.CognitoAuthentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Serilog;
using Newtonsoft.Json;
using System;

namespace TAP.Extranet.Areas.Identity.Pages.Account
{
    [AllowAnonymous]
    public class RegisterModel : PageModel
    {
        private readonly ILogger logger;

        private readonly SignInManager<CognitoUser> signInManager;
        private readonly CognitoUserManager<CognitoUser> userManager;
        private readonly CognitoUserPool userPool;

        public RegisterModel(
            ILogger logger,
            SignInManager<CognitoUser> signInManager,
            UserManager<CognitoUser> userManager,
            CognitoUserPool userPool
            )
        {
            this.logger = logger;
            this.userManager = userManager as CognitoUserManager<CognitoUser>;
            this.signInManager = signInManager;
            this.userPool = userPool;
        }

        [BindProperty]
        public RegisterViewModel Input { get; set; }

        public string ReturnUrl { get; set; }

        public async Task OnGet(string returnUrl = null)
        {
            ReturnUrl = returnUrl;
        }

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = userPool.GetUser(Input.Email);

                user.Attributes.Add(CognitoAttributesConstants.Name, Input.Name);
                user.Attributes.Add(CognitoAttributesConstants.FamilyName, Input.Surname);
                user.Attributes.Add(CognitoAttributesConstants.Email, Input.Email);

                user.Attributes.Add(ExtranetUserAttributes.OperatorName, Input.BusinessName);
                user.Attributes.Add(ExtranetUserAttributes.Approved, "0");

                var signInResult = await this.userManager.CreateAsync(user, Input.Password);

                if (signInResult.Succeeded)
                {
                    this.logger.Information($"New user account created: {JsonConvert.SerializeObject(Input)}");
                    RedirectToAction("Index", "Home");
                }

                this.logger.Warning($"Unable to create new user account! Errors: {string.Join("\n\r", signInResult.Errors)}. User details: {JsonConvert.SerializeObject(Input)}");

                foreach (var error in signInResult.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }
    }
}

User Pool settings:

image

When calling await this.userManager.CreateAsync(user, Input.Password) I get the following exception:

Missing Authentication Token
at Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\ErrorHandler\HttpErrorResponseExceptionHandler.cs:line 60
at Amazon.Runtime.Internal.ErrorHandler.ProcessException(IExecutionContext executionContext, Exception exception) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\ErrorHandler\ErrorHandler.cs:line 212
at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\ErrorHandler\ErrorHandler.cs:line 104
at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync[T](IExecutionContext executionContext) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\Handlers\CredentialsRetriever.cs:line 98
at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.RetryHandler.InvokeAsync[T](IExecutionContext executionContext) in E:\JenkinsWorkspaces\v3-trebuchet-release\AWSDotNetPublic\sdk\src\Core\Amazon.Runtime\Pipeline\RetryHandler\RetryHandler.cs:line 137
at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.CallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Runtime.Internal.MetricsHandler.InvokeAsync[T](IExecutionContext executionContext)
at Amazon.Extensions.CognitoAuthentication.CognitoUserPool.GetPasswordPolicyTypeAsync()
at Amazon.AspNetCore.Identity.Cognito.CognitoPasswordValidator.ValidateAsync(UserManager1 manager, CognitoUser user, String password) at Amazon.AspNetCore.Identity.Cognito.CognitoUserManager1.ValidatePasswordInternal(TUser user, String password)
at Amazon.AspNetCore.Identity.Cognito.CognitoUserManager1.CreateAsync(TUser user, String password, IDictionary2 validationData)
at Test.Areas.Identity.Pages.Account.RegisterModel.OnPostAsync(String returnUrl) in C:\Projects\Test\Areas\Identity\Pages\Account\Register.cshtml.cs:line 115

Am I missing something obvious? Sorry if I am but I've used this package elsewhere (which didn't include registration) and it just worked so I'm a bit stuck! Let me know if you need to see any details of the User Pool from Cognito.

email confirmation

In CognitoSignInManager
method
protected override async Task PreSignInCheck(TUser user)
{
// Checks for email/phone number confirmation status
if (!await CanSignInAsync(user).ConfigureAwait(false))
{
return SignInResult.NotAllowed;
}
if (await IsPasswordChangeRequiredAsync(user).ConfigureAwait(false))
{
return CognitoSignInResult.PasswordChangeRequired;
}
if (await IsPasswordResetRequiredAsync(user).ConfigureAwait(false))
{
return CognitoSignInResult.PasswordResetRequired;
}
return null;
}
Does not appear to actually check email confirmations status
If email is not confirmed signIn is allowed

Creating and Using Roles

Hello, this might not be the most appropriate place for this question and if it's not I'm sorry. I'm looking for at least a little direction to start. I want to include roles within my app. I don't see on cognito how I add the role nor code for retrieving it. Can anyone at least point me in a good direction?

Thanks!

User Registration Exception

Thanks in advanced for helping!

During user registration I am getting an exception, "Operation Cancelled" right here: var result = await _userManager.CreateAsync(user, Input.Password);

Is it possible I don't have something configured correctly in my user pool? I basically created the pool with all default values except I created a clientAPP. Also, I essentially copied the samples as they were. I'm extremely new to aws and authentication.

image

image

Authorization always fails with 404

I've implemented the authorization exactly as described in the Readme, but when I use the [Authorize] attribute for any controller method, I always get the following error:

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker: Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult: Information: Executing ChallengeResult with authentication schemes ().
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler: Information: AuthenticationScheme: Identity.Application was challenged.

Somehow it seems that the access token is not even validated. Any comments?

Here is are the relevant snippets from my startup.cs:

In ConfigureServices:

var cognitoIdentityProvider = new AmazonCognitoIdentityProviderClient((RegionEndpoint.EUCentral1);
            var cognitoUserPool = new CognitoUserPool("<MyUserPoolId>", "<MyClientId>", cognitoIdentityProvider);
            services.AddSingleton<IAmazonCognitoIdentityProvider>(cognitoIdentityProvider);
            services.AddSingleton(cognitoUserPool);
            services.AddCognitoIdentity();

In Configure:
app.UseAuthentication();

I'm using Amazon.AspNetCore.Identity.Cognito v1.0.0 and Amazon.Extensions.CognitoAuthentication v1.0.3

Thanks! Any help is appreciated.

Reset password flow

What's the correct flow for when a password is reset in Cognito (AWS console or otherwise)? When I do this and sign in I get a RequiresPasswordChange = true response as expected but when I subsequently call userManager.ChangePasswordAsync() with the user, old password and new password I then get the following error:

Failed to change the Cognito User password : Password reset required for the user

I thought that maybe I should be using ResetPasswordAsync instead but there doesn't seem to be a way of discerning between when a ChangePassword is required and when a ResetPassword is required based on the log in result. Both the result for an admin-created user's first login and a when a user's password has been reset by an admin is RequiresPasswordChange = true.

Thanks

Confirm Email Change

Hi, so I'm trying to enable email change on my app, and I managed to create an email confirmation page by replicating components from the ConfirmAccount and ConfirmEmail models to create the OnPostAsync method below:

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

                var user = await _userManager.FindByIdAsync(userId);
                if (user == null)
                {
                    return NotFound($"Unable to load user with ID '{userId}'.");
                }

                var result = await _userManager.ConfirmEmailAsync(user, Input.Code);
                if (!result.Succeeded)
                {
                    throw new InvalidOperationException($"Error confirming email for user with ID '{userId}':");
                }
                else
                {
                    return returnUrl != null ? LocalRedirect(returnUrl) : Page() as IActionResult;
                }
            }

            return Page();
        }
    }

The problem, though, is that I'm receiving a "Failed to verify the attribute for the Cognito User : 1 validation error detected: Value at 'accessToken' failed to satisfy constraint: Member must satisfy regular expression pattern: [A-Za-z0-9-_=.]+" error when ConfirmEmailAsync is called and I'm not sure why.

The operation was canceled.

Hi,
I downloaded the sample app, and changed the AWS settings to the ones below
(I changed a bunch of letters and numbers so these aren't real credentials here)

And I get this error when I try to log in:
OperationCanceledException: The operation was canceled.
System.Net.Http.HttpClient.HandleFinishSendAsyncError(Exception e, CancellationTokenSource cts)

Any idea what I am doing wrong?

"Region": "us-east-1",
"UserPoolClientId": "6i5aljnb2k7ckl4ye5ko32lk1y",
"UserPoolClientSecret": "47jickio4legsvhcrfg0g67p890ndt5ouspl0i2lop8a3juht24gj",
"UserPoolId": "us-east-1_ws5AjVfgt"

How to implement ChangePassword process

Following on from #35, I'm attempting to implement a process for the account status FORCE_CHANGE_PASSWORD..

As far as I can tell, when getting a result from a login of cognitoResult.RequiresPasswordChange, the user is not authenticated. I can't find a way to allow the user to reset their own password when we get in this state. I've tried:

var user = await _userManager.FindByEmailAsync(Input.Email).ConfigureAwait(false);
user.ChangePasswordAsync(......)

This fails becuase the user isn't authenticated.

I've also tried to use the password reset process, but this also fails with the error
NotAuthorizedException: User password cannot be reset in the current state.

The current state is FORCE_CHANGE_PASSWORD, with the email verified, as entered via the aws console.

Am I missing something obvious?

Help Wanted - Request Signature We Calculated Does Not Match

"AWS": {
"Region": "Value Entered is: us-east-1",
"UserPoolClientId": "Value Entered is: User Pool -> My Pool -> App Client Id",
"UserPoolClientSecret": "Value Entered is: User Pool -> My Pool -> App Client Secret",
"UserPoolId": "Value Entered is: General Settings - Pool Id"
},
"AllowedHosts": "*"
} Run the register postback. I get this error.

An unhandled exception occurred while processing the request.
HttpErrorResponseException: Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown.
Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken) in HttpRequestMessageFactory.cs, line 539

AmazonCognitoIdentityProviderException: The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
Amazon.Runtime.Internal.HttpErrorResponseExceptionHandler.HandleException(IExecutionContext executionContext, HttpErrorResponseException exception) in HttpErrorResponseExceptionHandler.cs, line 60

I have looked pretty closely. Can't see anything wrong with the implementation. It seems like I have the correct credentials entered. My next step is to download the source for this provider code and start digging through the source code.

Before I go down that road, any suggestions would be appreciated. Am I missing something?

Register or SignIn - OperationCanceledException: The operation was canceled

I am trying to implement the this library and have taken the exact samples and simply added my AWS block to the appsetting.Development.json file:

"AWS": { "Region": "us-east-1", "UserPoolClientId": "<my client id>", "UserPoolClientSecret": "<my secret>", "UserPoolId": "<my user pool id>" }

No matter whether I call CreateAsync or PasswordSignInAsync, after exactly 5 seconds I receive the error below. Im pulling my hair out because something obviously bad is happening but the stack error is useless telling me it was cancelled. Im certain its something stupid I missed but the error stack is not helpful at all. I using .Net Core2, VS 2017 and everything compiles just fine and runs, no changes were made to the samples other than to add my AWS section to the appsettings:

OperationCanceledException: The operation was canceled. System.Net.Http.HttpClient.HandleFinishSendAsyncError(Exception e, CancellationTokenSource cts) System.Net.Http.HttpClient.FinishSendAsyncUnbuffered(Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts) System.Net.Http.HttpClient.GetStringAsyncCore(Task<HttpResponseMessage> getTask) Amazon.Runtime.Internal.Util.AsyncHelpers+<>c__DisplayClass1_1<T>+<<RunSync>b__0>d.MoveNext() Amazon.Runtime.Internal.Util.AsyncHelpers+ExclusiveSynchronizationContext.BeginMessageLoop() in AsyncHelpers.cs Amazon.Runtime.Internal.Util.AsyncHelpers.RunSync<T>(Func<Task<T>> task) in AsyncHelpers.cs Amazon.Util.AWSSDKUtils.DownloadStringContent(Uri uri, TimeSpan timeout, IWebProxy proxy) in AWSSDKUtils.cs Amazon.Util.EC2InstanceMetadata.GetItems(string relativeOrAbsolutePath, int tries, bool slurp) in EC2InstanceMetadata.cs Amazon.Util.EC2InstanceMetadata.get_IAMSecurityCredentials() in EC2InstanceMetadata.cs Amazon.Runtime.DefaultInstanceProfileAWSCredentials.FetchCredentials() in DefaultInstanceProfileAWSCredentials.cs Amazon.Runtime.DefaultInstanceProfileAWSCredentials.GetCredentials() in DefaultInstanceProfileAWSCredentials.cs Amazon.Runtime.DefaultInstanceProfileAWSCredentials.GetCredentialsAsync() in DefaultInstanceProfileAWSCredentials.cs Amazon.Runtime.Internal.CredentialsRetriever.InvokeAsync<T>(IExecutionContext executionContext) in CredentialsRetriever.cs Amazon.Runtime.Internal.RetryHandler.InvokeAsync<T>(IExecutionContext executionContext) Amazon.Runtime.Internal.RetryHandler.InvokeAsync<T>(IExecutionContext executionContext) in RetryHandler.cs Amazon.Runtime.Internal.CallbackHandler.InvokeAsync<T>(IExecutionContext executionContext) Amazon.Runtime.Internal.CallbackHandler.InvokeAsync<T>(IExecutionContext executionContext) Amazon.Runtime.Internal.ErrorCallbackHandler.InvokeAsync<T>(IExecutionContext executionContext) Amazon.Runtime.Internal.MetricsHandler.InvokeAsync<T>(IExecutionContext executionContext) Amazon.Extensions.CognitoAuthentication.CognitoUserPool.GetPasswordPolicyTypeAsync() Amazon.AspNetCore.Identity.Cognito.CognitoPasswordValidator.ValidateAsync(UserManager<CognitoUser> manager, CognitoUser user, string password) Amazon.AspNetCore.Identity.Cognito.CognitoUserManager<TUser>.ValidatePasswordInternal(TUser user, string password) Amazon.AspNetCore.Identity.Cognito.CognitoUserManager<TUser>.CreateAsync(TUser user, string password, IDictionary<string, string> validationData) Samples.Areas.Identity.Pages.Account.RegisterModel.OnPostAsync(string returnUrl) in Register.cshtml.cs + IdentityResult result = await _userManager.CreateAsync(user, Input.Password); Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory+GenericTaskHandlerMethod.Convert<T>(object taskAsObject) Microsoft.AspNetCore.Mvc.RazorPages.Internal.ExecutorFactory+GenericTaskHandlerMethod.Execute(object receiver, object[] arguments) Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeHandlerMethodAsync() Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeNextPageFilterAsync() Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Rethrow(PageHandlerExecutedContext context) Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.RazorPages.Internal.PageActionInvoker.InvokeInnerFilterAsync() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync() Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync() Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context) Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

ETA on when production ready?

Hi,

I'm looking to integrate with Cognito using Identity from a C# Web API and this looks like exactly what I need. I see that it's still in development. Is there an estimate on when this will be ready for production?

Thanks!

Operation canceled exception when trying to use AdminDeleteUserAsync

var deleteUserRequest = new AdminDeleteUserRequest { Username = username, UserPoolId = _poolId};
var config = new AmazonCognitoIdentityProviderConfig { RegionEndpoint = Amazon.RegionEndpoint.EUWest1 };
var adminDeleteUserResponse = await new AmazonCognitoIdentityProviderClient(config)
                                                        .AdminDeleteUserAsync(deleteUserRequest);

Executing the code above is throwing an exception ("The operation was canceled.")

I wonder if this is related to issue 41?

I tried some of the advice mentioned on the other issue like passing an access key and secret (which I don't want to do anyway) and also adding the "AmazonCognitoPowerUser" policy to my IAM account but then I got a different exception stating:

User: arn:aws:iam::123546789:user/xxxxxxx is not authorized to perform: cognito-idp:AdminDeleteUser on resource: arn:aws:cognito-idp:eu-west-1:123456789:userpool/eu-west-1_1xxxxx with an explicit deny"

If the issues are related is there any ETA on a fix? If they're not, do you have any suggestions on how I could get this to work.

Thanks

custom attributes

When registering a new user I wish to set a custom attribute
var user = _pool.GetUser(Input.Email);
user.Attributes.Add(CognitoAttribute.Email.AttributeName, Input.Email);
user.Attributes.Add(CognitoAttribute.GivenName.AttributeName, Input.GivenName);
user.Attributes.Add(CognitoAttribute.FamilyName.AttributeName, Input.FamilyName);
user.Attributes.Add("custom:site", "somevalue");
I have custome:site registered as a custom attribute however I get error when I run it.
"Failed to create the Cognito User : A client attempted to write unauthorized attribute"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.