repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.CognitoIdentityProvider; using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Protocols.OpenIdConnect; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; namespace Amazon.AspNetCore.Identity.Cognito { public class CognitoUserManager<TUser> : UserManager<TUser> where TUser : CognitoUser { // This specific type is needed to accomodate all the interfaces it implements. private readonly CognitoUserStore<TUser> _userStore; private IHttpContextAccessor _httpContextAccessor; public CognitoUserManager(IUserStore<TUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<TUser> passwordHasher, IEnumerable<IUserValidator<TUser>> userValidators, IEnumerable<IPasswordValidator<TUser>> passwordValidators, CognitoKeyNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<TUser>> logger, IHttpContextAccessor httpContextAccessor) : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger) { var userStore = store as CognitoUserStore<TUser>; if (userStore == null) { throw new ArgumentException("The store must be of type CognitoUserStore<TUser>", nameof(store)); } else { _userStore = userStore; } _httpContextAccessor = httpContextAccessor ?? throw new ArgumentException(nameof(httpContextAccessor)); } /// <summary> /// Gets the user, if any, associated with the normalized value of the specified email address. /// </summary> /// <param name="email">The email address to return the user for.</param> /// <returns> /// The task object containing the results of the asynchronous lookup operation, the user, if any, associated with a normalized value of the specified email address. /// </returns> public override async Task<TUser> FindByEmailAsync(string email) { ThrowIfDisposed(); if (email == null) { throw new ArgumentNullException(nameof(email)); } #if NETCOREAPP3_1 email = NormalizeEmail(email); #endif #if NETSTANDARD2_0 email = NormalizeKey(email); #endif var user = await _userStore.FindByEmailAsync(email, CancellationToken).ConfigureAwait(false); if (user != null) { await PopulateTokens(user, ClaimTypes.Email, email).ConfigureAwait(false); } return user; } /// <summary> /// Finds and returns a user, if any, who has the specified <paramref name="userId"/>. /// </summary> /// <param name="userId">The user ID to search for.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the user matching the specified <paramref name="userId"/> if it exists. /// </returns> public override async Task<TUser> FindByIdAsync(string userId) { ThrowIfDisposed(); if (userId == null) { throw new ArgumentNullException(nameof(userId)); } var user = await _userStore.FindByIdAsync(userId, CancellationToken).ConfigureAwait(false); if (user != null) { await PopulateTokens(user, ClaimTypes.Name, userId).ConfigureAwait(false); } return user; } /// <summary> /// Finds and returns a user, if any, who has the specified user name. /// </summary> /// <param name="userName">The user name to search for.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the user matching the specified <paramref name="userName"/> if it exists. /// </returns> public override async Task<TUser> FindByNameAsync(string userName) { ThrowIfDisposed(); if (userName == null) { throw new ArgumentNullException(nameof(userName)); } #if NETCOREAPP3_1 userName = NormalizeName(userName); #endif #if NETSTANDARD2_0 userName = NormalizeKey(userName); #endif var user = await _userStore.FindByNameAsync(userName, CancellationToken).ConfigureAwait(false); if (user != null) { await PopulateTokens(user, ClaimTypes.Name, userName).ConfigureAwait(false); } return user; } /// <summary> /// Populates the user SessionToken object if they satisfy the claimType and claimValue parameters /// </summary> /// <param name="user">The user to populate tokens for.</param> /// <param name="claimType">The claim type to check.</param> /// <param name="claimValue">The claim value to check.</param> private async Task PopulateTokens(TUser user, string claimType, string claimValue) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } // First check if the current user is authenticated before calling AuthenticateAsync() or the call may hang. if (_httpContextAccessor?.HttpContext?.User?.Identity?.IsAuthenticated == true) { var result = await _httpContextAccessor.HttpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme).ConfigureAwait(false); if (result?.Principal?.Claims != null) { if (result.Principal.Claims.Any(claim => claim.Type == claimType && claim.Value == claimValue)) { var accessToken = await _httpContextAccessor.HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken).ConfigureAwait(false); var refreshToken = await _httpContextAccessor.HttpContext.GetTokenAsync(OpenIdConnectParameterNames.RefreshToken).ConfigureAwait(false); var idToken = await _httpContextAccessor.HttpContext.GetTokenAsync(OpenIdConnectParameterNames.IdToken).ConfigureAwait(false); user.SessionTokens = new CognitoUserSession(idToken, accessToken, refreshToken, result.Properties.IssuedUtc.Value.UtcDateTime, result.Properties.ExpiresUtc.Value.UtcDateTime); } } } } /// <summary> /// Returns an AuthFlowResponse representing an authentication workflow for the specified <paramref name="password"/> /// and the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose password should be validated.</param> /// <param name="password">The password to validate</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the AuthFlowResponse object /// if the specified <paramref name="password" /> matches the one store for the <paramref name="user"/>, /// otherwise null.</returns> public virtual Task<AuthFlowResponse> CheckPasswordAsync(TUser user, string password) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return _userStore.StartValidatePasswordAsync(user, password, CancellationToken); } /// <summary> /// Checks if the <param name="user"> can log in with the specified 2fa code challenge <paramref name="code"/>. /// </summary> /// <param name="user">The user try to log in with.</param> /// <param name="code">The 2fa code to check</param> /// <param name="authWorkflowSessionId">The ongoing Cognito authentication workflow id.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the AuthFlowResponse object linked to that authentication workflow.</returns> public virtual Task<AuthFlowResponse> RespondToTwoFactorChallengeAsync(TUser user, string code, string authWorkflowSessionId) { return RespondToTwoFactorChallengeAsync(user, code, ChallengeNameType.SMS_MFA, authWorkflowSessionId); } /// <summary> /// Checks if the <param name="user"> can log in with the specified 2fa code challenge <paramref name="code"/>. /// </summary> /// <param name="user">The user try to log in with.</param> /// <param name="code">The 2fa code to check</param> /// <param name="challengeNameType">The ongoing Cognito challenge name type.</param> /// <param name="authWorkflowSessionId">The ongoing Cognito authentication workflow id.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the AuthFlowResponse object linked to that authentication workflow.</returns> public virtual Task<AuthFlowResponse> RespondToTwoFactorChallengeAsync(TUser user, string code, ChallengeNameType challengeNameType, string authWorkflowSessionId) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return _userStore.RespondToTwoFactorChallengeAsync(user, code, challengeNameType, authWorkflowSessionId, CancellationToken); } /// <summary> /// Sets a flag indicating whether the specified <paramref name="user"/> has two factor authentication enabled or not, /// as an asynchronous operation. /// </summary> /// <param name="user">The user whose two factor authentication enabled status should be set.</param> /// <param name="enabled">A flag indicating whether the specified <paramref name="user"/> has two factor authentication enabled.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, the <see cref="IdentityResult"/> of the operation /// </returns> public override async Task<IdentityResult> SetTwoFactorEnabledAsync(TUser user, bool enabled) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } await _userStore.SetTwoFactorEnabledAsync(user, enabled, CancellationToken).ConfigureAwait(false); return IdentityResult.Success; } /// <summary> /// Changes a user's password after confirming the specified <paramref name="currentPassword"/> is correct, /// as an asynchronous operation. /// </summary> /// <param name="user">The user whose password should be set.</param> /// <param name="currentPassword">The current password to validate before changing.</param> /// <param name="newPassword">The new password to set for the specified <paramref name="user"/>.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public override Task<IdentityResult> ChangePasswordAsync(TUser user, string currentPassword, string newPassword) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return _userStore.ChangePasswordAsync(user, currentPassword, newPassword, CancellationToken); } /// <summary> /// Checks if the password needs to be changed for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user to check if the password needs to be changed.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing a boolean set to true if the password needs to be changed, false otherwise.</returns> public virtual Task<bool> IsPasswordChangeRequiredAsync(TUser user) { ThrowIfDisposed(); return _userStore.IsPasswordChangeRequiredAsync(user, CancellationToken); } /// <summary> /// Checks if the password needs to be reset for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user to check if the password needs to be reset.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing a boolean set to true if the password needs to be reset, false otherwise.</returns> public virtual Task<bool> IsPasswordResetRequiredAsync(TUser user) { ThrowIfDisposed(); return _userStore.IsPasswordResetRequiredAsync(user, CancellationToken); } /// <summary> /// Resets the <paramref name="user"/>'s password to the specified <paramref name="newPassword"/> after /// validating the given password reset <paramref name="token"/>. /// </summary> /// <param name="user">The user whose password should be reset.</param> /// <param name="token">The password reset token to verify.</param> /// <param name="newPassword">The new password to set if reset token verification succeeds.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public override Task<IdentityResult> ResetPasswordAsync(TUser user, string token, string newPassword) { ThrowIfDisposed(); return _userStore.ChangePasswordWithTokenAsync(user, token, newPassword, CancellationToken); } /// <summary> /// Resets the <paramref name="user"/>'s password and sends the confirmation token to the user /// via email or sms depending on the user pool policy. /// </summary> /// <param name="user">The user whose password should be reset.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public Task<IdentityResult> ResetPasswordAsync(TUser user) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return _userStore.ResetPasswordAsync(user, CancellationToken); } /// <summary> /// Creates the specified <paramref name="user"/> in Cognito with a generated password sent to the user, /// as an asynchronous operation. /// </summary> /// <param name="user">The user to create.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public override Task<IdentityResult> CreateAsync(TUser user) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return _userStore.CreateAsync(user, CancellationToken); } /// <summary> /// Creates the specified <paramref name="user"/> in Cognito with the given password, /// as an asynchronous operation. /// </summary> /// <param name="user">The user to create.</param> /// <param name="password">The password for the user.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public override Task<IdentityResult> CreateAsync(TUser user, string password) { ThrowIfDisposed(); return CreateAsync(user, password, null); } /// <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) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (password == null) { throw new ArgumentNullException(nameof(password)); } var validate = await ValidatePasswordInternal(user, password).ConfigureAwait(false); if (!validate.Succeeded) { return validate; } var result = await _userStore.CreateAsync(user, password, validationData, CancellationToken).ConfigureAwait(false); return result; } /// <summary> /// Validates the given password against injected IPasswordValidator password validators, /// as an asynchronous operation. /// </summary> /// <param name="user">The user to validate the password for.</param> /// <param name="password">The password to validate.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> private async Task<IdentityResult> ValidatePasswordInternal(TUser user, string password) { var errors = new List<IdentityError>(); foreach (var v in PasswordValidators) { var result = await v.ValidateAsync(this, user, password).ConfigureAwait(false); if (!result.Succeeded) { errors.AddRange(result.Errors); } } if (errors.Count > 0) { Logger.LogWarning(14, "User {userId} password validation failed: {errors}.", await GetUserIdAsync(user).ConfigureAwait(false), string.Join(";", errors.Select(e => e.Code))); return IdentityResult.Failed(errors.ToArray()); } return IdentityResult.Success; } /// <summary> /// Generates an email confirmation token for the specified user. /// </summary> /// <param name="user">The user to generate an email confirmation token for.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, an email confirmation token. /// </returns> public override Task<string> GenerateEmailConfirmationTokenAsync(TUser user) { throw new NotSupportedException("Cognito does not support directly retrieving the token value. Use SendEmailConfirmationTokenAsync() instead."); } /// <summary> /// Generates a telephone number change token for the specified user. /// </summary> /// <param name="user">The user to generate a telephone number token for.</param> /// <param name="phoneNumber">The new phone number the validation token should be sent to.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the telephone change number token. /// </returns> public override Task<string> GenerateChangePhoneNumberTokenAsync(TUser user, string phoneNumber) { throw new NotSupportedException("Cognito does not support directly retrieving the token value. Use SendPhoneConfirmationTokenAsync() instead."); } /// <summary> /// Generates and sends an email confirmation token for the specified user. /// </summary> /// <param name="user">The user to generate and send an email confirmation token for.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public virtual Task<IdentityResult> SendEmailConfirmationTokenAsync(TUser user) { ThrowIfDisposed(); return _userStore.GetUserAttributeVerificationCodeAsync(user, CognitoAttribute.Email.AttributeName, CancellationToken); } /// <summary> /// Generates and sends a phone confirmation token for the specified user. /// </summary> /// <param name="user">The user to generate and send a phone confirmation token for.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public virtual Task<IdentityResult> SendPhoneConfirmationTokenAsync(TUser user) { ThrowIfDisposed(); return _userStore.GetUserAttributeVerificationCodeAsync(user, CognitoAttribute.PhoneNumber.AttributeName, CancellationToken); } /// <summary> /// Confirms the email of an user by validating that an email confirmation token is valid for the specified <paramref name="user"/>. /// This operation requires a logged in user. /// </summary> /// <param name="user">The user to validate the token against.</param> /// <param name="confirmationCode">The email confirmation code to validate.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public override Task<IdentityResult> ConfirmEmailAsync(TUser user, string confirmationCode) { ThrowIfDisposed(); return _userStore.VerifyUserAttributeAsync(user, CognitoAttribute.Email.AttributeName, confirmationCode, CancellationToken); } /// <summary> /// Confirms the phone number of an user by validating that an email confirmation token is valid for the specified <paramref name="user"/>. /// This operation requires a logged in user. /// </summary> /// <param name="user">The user to validate the token against.</param> /// <param name="confirmationCode">The phone number confirmation code to validate.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public Task<IdentityResult> ConfirmPhoneNumberAsync(TUser user, string confirmationCode) { ThrowIfDisposed(); return _userStore.VerifyUserAttributeAsync(user, CognitoAttribute.PhoneNumber.AttributeName, confirmationCode, CancellationToken); } /// <summary> /// Confirms the specified <paramref name="user"/> account with the specified /// <paramref name="confirmationCode"/> they were sent by email or sms, /// as an asynchronous operation. /// When a new user is confirmed, the user's attribute through which the /// confirmation code was sent (email address or phone number) is marked as verified. /// If this attribute is also set to be used as an alias, then the user can sign in with /// that attribute (email address or phone number) instead of the username. /// </summary> /// <param name="user">The user to confirm.</param> /// <param name="confirmationCode">The confirmation code that was sent by email or sms.</param> /// <param name="forcedAliasCreation">If set to true, this resolves potential alias conflicts by marking the attribute email or phone number verified. /// If set to false and an alias conflict exists, then the user confirmation will fail.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public virtual Task<IdentityResult> ConfirmSignUpAsync(TUser user, string confirmationCode, bool forcedAliasCreation) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrWhiteSpace(confirmationCode)) { throw new ArgumentException("The confirmation code can not be null or blank", nameof(confirmationCode)); } return _userStore.ConfirmSignUpAsync(user, confirmationCode, forcedAliasCreation, CancellationToken); } /// <summary> /// Admin confirms the specified <paramref name="user"/> /// as an asynchronous operation. /// </summary> /// <param name="user">The user to confirm.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public virtual Task<IdentityResult> AdminConfirmSignUpAsync(TUser user) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return _userStore.AdminConfirmSignUpAsync(user, CancellationToken); } /// <summary> /// Resends the account signup confirmation code for the specified <paramref name="user"/> /// as an asynchronous operation. /// </summary> /// <param name="user">The user to resend the account signup confirmation code for.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public virtual Task<IdentityResult> ResendSignupConfirmationCodeAsync(TUser user) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return _userStore.ResendSignupConfirmationCodeAsync(user, CancellationToken); } /// <summary> /// Sets the phone number for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user whose phone number to set.</param> /// <param name="phoneNumber">The phone number to set.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public override async Task<IdentityResult> SetPhoneNumberAsync(TUser user, string phoneNumber) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } await _userStore.SetPhoneNumberAsync(user, phoneNumber, CancellationToken).ConfigureAwait(false); return await UpdateUserAsync(user).ConfigureAwait(false); } /// <summary> /// Sets the <paramref name="email"/> address for a <paramref name="user"/>. /// </summary> /// <param name="user">The user whose email should be set.</param> /// <param name="email">The email to set.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public override async Task<IdentityResult> SetEmailAsync(TUser user, string email) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } await _userStore.SetEmailAsync(user, email, CancellationToken).ConfigureAwait(false); return await UpdateUserAsync(user).ConfigureAwait(false); } /// <summary> /// Updates a users emails if the specified email change <paramref name="token"/> is valid for the user. /// </summary> /// <param name="user">The user whose email should be updated.</param> /// <param name="newEmail">The new email address.</param> /// <param name="token">The change email token to be verified.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public override Task<IdentityResult> ChangeEmailAsync(TUser user, string newEmail, string token) { throw new NotSupportedException("Cognito does not support changing and confirming the email simultaneously, use SetEmailAsync() and ConfirmEmailAsync()"); } /// <summary> /// Updates the user attributes. /// </summary> /// <param name="user">The user with the new attributes values changed.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> protected override Task<IdentityResult> UpdateUserAsync(TUser user) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return _userStore.UpdateAsync(user, CancellationToken); } /// <summary> /// Not supported: Returns an IQueryable of users if the store is an IQueryableUserStore /// </summary> public override IQueryable<TUser> Users => throw new NotSupportedException("This property is not supported. Use GetUsersAsync() instead."); /// <summary> /// Queries Cognito and returns the users in the pool. Optional filters can be applied on the users to retrieve based on their attributes. /// Providing an empty attributeFilterName parameter returns all the users in the pool. /// </summary> /// <param name="attributeFilterName"> The attribute name to filter your search on. You can only search for the following standard attributes: /// username (case-sensitive) /// email /// phone_number /// name /// given_name /// family_name /// preferred_username /// cognito:user_status (called Status in the Console) (case-insensitive) /// status (called Enabled in the Console) (case-sensitive) /// sub /// Custom attributes are not searchable. /// For more information, see Searching for Users Using the ListUsers API and Examples /// of Using the ListUsers API in the Amazon Cognito Developer Guide.</param> /// <param name="attributeFilterType"> The type of filter to apply: /// For an exact match, use = /// For a prefix ("starts with") match, use ^= /// </param> /// <param name="attributeFilterValue"> The filter value for the specified attribute.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing a IEnumerable of CognitoUser. /// </returns> public virtual Task<IEnumerable<CognitoUser>> GetUsersAsync(CognitoAttribute filterAttribute = null, CognitoAttributeFilterType filterType = null, string filterValue = "") { ThrowIfDisposed(); return _userStore.GetUsersAsync(filterAttribute, filterType, filterValue, CancellationToken); } /// <summary> /// Adds the specified <paramref name="claims"/> to the <paramref name="user"/>. /// </summary> /// <param name="user">The user to add the claim to.</param> /// <param name="claims">The claims to add.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public override async Task<IdentityResult> AddClaimsAsync(TUser user, IEnumerable<Claim> claims) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (claims == null) { throw new ArgumentNullException(nameof(claims)); } await _userStore.AddClaimsAsync(user, claims, CancellationToken).ConfigureAwait(false); return IdentityResult.Success; } /// <summary> /// Removes the specified <paramref name="claims"/> from the given <paramref name="user"/>. /// </summary> /// <param name="user">The user to remove the specified <paramref name="claims"/> from.</param> /// <param name="claims">A collection of <see cref="Claim"/>s to remove.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public override async Task<IdentityResult> RemoveClaimsAsync(TUser user, IEnumerable<Claim> claims) { ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (claims == null) { throw new ArgumentNullException(nameof(claims)); } await _userStore.RemoveClaimsAsync(user, claims, CancellationToken).ConfigureAwait(false); return IdentityResult.Success; } } }
751
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.AspNetCore.Identity.Cognito.Exceptions; using Amazon.CognitoIdentityProvider; using Amazon.CognitoIdentityProvider.Model; using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Amazon.AspNetCore.Identity.Cognito { public partial class CognitoUserStore<TUser> : IUserCognitoStore<TUser> where TUser : CognitoUser { private const string UserStatusForceChangePassword = "FORCE_CHANGE_PASSWORD"; private const string UserStatusResetRequired = "RESET_REQUIRED"; private IAmazonCognitoIdentityProvider _cognitoClient; private CognitoUserPool _pool; private CognitoIdentityErrorDescriber _errorDescribers; public CognitoUserStore(IAmazonCognitoIdentityProvider cognitoClient, CognitoUserPool pool, IdentityErrorDescriber errors) { _cognitoClient = cognitoClient ?? throw new ArgumentNullException(nameof(cognitoClient)); _pool = pool ?? throw new ArgumentNullException(nameof(pool)); // IdentityErrorDescriber provides predefined error strings such as PasswordMismatch() or InvalidUserName(String) // This is used when returning an instance of IdentityResult, which can be constructed with an array of errors to be surfaced to the UI. if (errors == null) throw new ArgumentNullException(nameof(errors)); if (errors is CognitoIdentityErrorDescriber) _errorDescribers = errors as CognitoIdentityErrorDescriber; else throw new ArgumentException("The IdentityErrorDescriber must be of type CognitoIdentityErrorDescriber", nameof(errors)); } #region IUserCognitoStore /// <summary> /// Checks if the <param name="user"> can log in with the specified password <paramref name="password"/>. /// </summary> /// <param name="user">The user try to log in with.</param> /// <param name="password">The password supplied for validation.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the AuthFlowResponse object linked to that authentication workflow.</returns> public virtual async Task<AuthFlowResponse> StartValidatePasswordAsync(TUser user, string password, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { AuthFlowResponse context = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest() { Password = password }).ConfigureAwait(false); return context; } catch (NotAuthorizedException) { // If the password validation fails then the response flow should be set to null. return null; } } /// <summary> /// Checks if the <param name="user"> can log in with the specified 2fa code challenge <paramref name="code"/>. /// </summary> /// <param name="user">The user try to log in with.</param> /// <param name="code">The 2fa code to check</param> /// <param name="authWorkflowSessionId">The ongoing Cognito authentication workflow id.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the AuthFlowResponse object linked to that authentication workflow.</returns> public virtual async Task<AuthFlowResponse> RespondToTwoFactorChallengeAsync(TUser user, string code, string authWorkflowSessionId, CancellationToken cancellationToken) { return await RespondToTwoFactorChallengeAsync(user, code, ChallengeNameType.SMS_MFA, authWorkflowSessionId, cancellationToken).ConfigureAwait(false); } /// <summary> /// Checks if the <param name="user"> can log in with the specified 2fa code challenge <paramref name="code"/>. /// </summary> /// <param name="user">The user try to log in with.</param> /// <param name="code">The 2fa code to check</param> /// <param name="challengeNameType">The ongoing Cognito authentication challenge name type.</param> /// <param name="authWorkflowSessionId">The ongoing Cognito authentication workflow id.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the AuthFlowResponse object linked to that authentication workflow.</returns> public virtual async Task<AuthFlowResponse> RespondToTwoFactorChallengeAsync(TUser user, string code, ChallengeNameType challengeNameType, string authWorkflowSessionId, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { AuthFlowResponse context = await user.RespondToMfaAuthAsync(new RespondToMfaRequest() { SessionID = authWorkflowSessionId, MfaCode = code, ChallengeNameType = challengeNameType }).ConfigureAwait(false); return context; } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to respond to Cognito two factor challenge.", e); } } /// <summary> /// Changes the password on the cognito account associated with the <paramref name="user"/>. /// </summary> /// <param name="user">The user to change the password for.</param> /// <param name="currentPassword">The current password of the user.</param> /// <param name="newPassword">The new passord for the user.</param> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string currentPassword, string newPassword, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { // We start an auth process as the user needs a valid session id to be able to change it's password. var authResult = await StartValidatePasswordAsync(user, currentPassword, cancellationToken).ConfigureAwait(false); if (authResult != null) { if (authResult.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED) { await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest() { SessionID = authResult.SessionID, NewPassword = newPassword }).ConfigureAwait(false); return IdentityResult.Success; } else if (user.SessionTokens != null && user.SessionTokens.IsValid()) // User is logged in, we can change his password { await user.ChangePasswordAsync(currentPassword, newPassword).ConfigureAwait(false); return IdentityResult.Success; } else return IdentityResult.Failed(_errorDescribers.PasswordMismatch()); } else return IdentityResult.Failed(_errorDescribers.PasswordMismatch()); } catch (AmazonCognitoIdentityProviderException e) { return IdentityResult.Failed(_errorDescribers.CognitoServiceError("Failed to change the Cognito User password", e)); } } /// <summary> /// Resets the <paramref name="user"/>'s password to the specified <paramref name="newPassword"/> after /// validating the given password reset <paramref name="token"/>. /// </summary> /// <param name="user">The user whose password should be reset.</param> /// <param name="token">The password reset token to verify.</param> /// <param name="newPassword">The new password to set if reset token verification succeeds.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public virtual async Task<IdentityResult> ChangePasswordWithTokenAsync(TUser user, string token, string newPassword, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { await _pool.ConfirmForgotPassword(user.Username, token, newPassword, cancellationToken).ConfigureAwait(false); return IdentityResult.Success; } catch (AmazonCognitoIdentityProviderException e) { return IdentityResult.Failed(_errorDescribers.CognitoServiceError("Failed to change the Cognito User password", e)); } } /// <summary> /// Checks if the password needs to be changed for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user to check if the password needs to be changed.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing a boolean set to true if the password needs to be changed, false otherwise.</returns> public virtual Task<bool> IsPasswordChangeRequiredAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); bool IsPasswordChangeRequired = user.Status.Equals(UserStatusForceChangePassword, StringComparison.InvariantCulture); return Task.FromResult(IsPasswordChangeRequired); } /// <summary> /// Checks if the password needs to be reset for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user to check if the password needs to be reset.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing a boolean set to true if the password needs to be reset, false otherwise.</returns> public virtual Task<bool> IsPasswordResetRequiredAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); bool IsPasswordResetRequired = user.Status.Equals(UserStatusResetRequired, StringComparison.InvariantCulture); return Task.FromResult(IsPasswordResetRequired); } /// <summary> /// Resets the <paramref name="user"/>'s password and sends the confirmation token to the user /// via email or sms depending on the user pool policy. /// </summary> /// <param name="user">The user to reset the password for.</param> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. public virtual async Task<IdentityResult> ResetPasswordAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var request = new AdminResetUserPasswordRequest { Username = user.Username, UserPoolId = _pool.PoolID }; try { await _cognitoClient.AdminResetUserPasswordAsync(request, cancellationToken).ConfigureAwait(false); return IdentityResult.Success; } catch (AmazonCognitoIdentityProviderException e) { return IdentityResult.Failed(_errorDescribers.CognitoServiceError("Failed to reset the Cognito User password", e)); } } /// <summary> /// Queries Cognito and returns the users in the pool. Optional filters can be applied on the users to retrieve based on their attributes. /// Providing an empty attributeFilterName parameter returns all the users in the pool. /// </summary> /// <param name="attributeFilterName"> The attribute name to filter your search on. You can only search for the following standard attributes: /// username (case-sensitive) /// email /// phone_number /// name /// given_name /// family_name /// preferred_username /// cognito:user_status (called Status in the Console) (case-insensitive) /// status (called Enabled in the Console) (case-sensitive) /// sub /// Custom attributes are not searchable. /// For more information, see Searching for Users Using the ListUsers API and Examples /// of Using the ListUsers API in the Amazon Cognito Developer Guide.</param> /// <param name="attributeFilterType"> The type of filter to apply: /// For an exact match, use = /// For a prefix ("starts with") match, use ^= /// </param> /// <param name="attributeFilterValue"> The filter value for the specified attribute.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing a IEnumerable of CognitoUser. /// </returns> public virtual async Task<IEnumerable<CognitoUser>> GetUsersAsync(CognitoAttribute attributeFilterName, CognitoAttributeFilterType attributeFilterType, string attributeFilterValue, CancellationToken cancellationToken) { var filter = ""; if (!string.IsNullOrWhiteSpace(attributeFilterName?.AttributeName)) { filter = (attributeFilterName.ToString() + attributeFilterType.ToString() + "\"" + attributeFilterValue + "\"").Trim(); } var request = new ListUsersRequest { UserPoolId = _pool.PoolID, Filter = filter }; ListUsersResponse response = null; var result = new List<CognitoUser>(); do { request.PaginationToken = response?.PaginationToken; try { response = await _cognitoClient.ListUsersAsync(request, cancellationToken).ConfigureAwait(false); } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to retrieve the list of users from Cognito.", e); } foreach (var user in response.Users) { result.Add(new CognitoUser(user.Username, _pool.ClientID, _pool, _cognitoClient, null, user.UserStatus.Value, user.Username, user.Attributes.ToDictionary(attribute => attribute.Name, attribute => attribute.Value))); } } while (!string.IsNullOrEmpty(response.PaginationToken)); return result; } /// <summary> /// Registers the specified <paramref name="user"/> in Cognito with the given password, /// as an asynchronous operation. Also submits the validation data to the pre sign-up lambda trigger. /// </summary> /// <param name="user">The user to create.</param> /// <param name="password">The password for the user to register with</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 virtual async Task<IdentityResult> CreateAsync(TUser user, string password, IDictionary<string, string> validationData, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { await _pool.SignUpAsync(user.UserID, password, user.Attributes, validationData).ConfigureAwait(false); return IdentityResult.Success; } catch (AmazonCognitoIdentityProviderException e) { return IdentityResult.Failed(_errorDescribers.CognitoServiceError("Failed to create the Cognito User", e)); } } /// <summary> /// Confirms the specified <paramref name="user"/> with the specified /// <paramref name="confirmationCode"/> they were sent by email or sms, /// as an asynchronous operation. /// When a new user is confirmed, the user's attribute through which the /// confirmation code was sent (email address or phone number) is marked as verified. /// If this attribute is also set to be used as an alias, then the user can sign in with /// that attribute (email address or phone number) instead of the username. /// </summary> /// <param name="user">The user to confirm.</param> /// <param name="confirmationCode">The confirmation code that was sent by email or sms.</param> /// <param name="forcedAliasCreation">If set to true, this resolves potential alias conflicts by marking the attribute email or phone number verified. /// If set to false and an alias conflict exists, then the user confirmation will fail.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public virtual async Task<IdentityResult> ConfirmSignUpAsync(TUser user, string confirmationCode, bool forcedAliasCreation, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { await user.ConfirmSignUpAsync(confirmationCode, forcedAliasCreation).ConfigureAwait(false); return IdentityResult.Success; } catch (AmazonCognitoIdentityProviderException e) { return IdentityResult.Failed(_errorDescribers.CognitoServiceError("Failed to confirm the Cognito User signup", e)); } } /// <summary> /// Admin confirms the specified <paramref name="user"/>, regardless of the confirmation code /// as an asynchronous operation. /// </summary> /// <param name="user">The user to confirm.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public virtual async Task<IdentityResult> AdminConfirmSignUpAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { await _cognitoClient.AdminConfirmSignUpAsync(new AdminConfirmSignUpRequest { Username = user.Username, UserPoolId = _pool.PoolID }, cancellationToken).ConfigureAwait(false); return IdentityResult.Success; } catch (AmazonCognitoIdentityProviderException e) { return IdentityResult.Failed(_errorDescribers.CognitoServiceError("Failed to admin confirm the Cognito User signup", e)); } } /// <summary> /// Resends the account signup confirmation code for the specified <paramref name="user"/> /// as an asynchronous operation. /// </summary> /// <param name="user">The user to resend the account signup confirmation code for.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public virtual async Task<IdentityResult> ResendSignupConfirmationCodeAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { await user.ResendConfirmationCodeAsync().ConfigureAwait(false); return IdentityResult.Success; } catch (AmazonCognitoIdentityProviderException e) { return IdentityResult.Failed(_errorDescribers.CognitoServiceError("Failed to resend the Cognito User signup confirmation code", e)); } } /// <summary> /// Generates and sends a verification code for the specified <paramref name="user"/>, /// and the specified <paramref name="attributeName"/>, /// as an asynchronous operation. /// This operation requires a logged in user. /// </summary> /// <param name="user">The user to send the verification code to.</param> /// <param name="attributeName">The attribute to verify.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public virtual async Task<IdentityResult> GetUserAttributeVerificationCodeAsync(TUser user, string attributeName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if(attributeName != CognitoAttribute.PhoneNumber.AttributeName && attributeName != CognitoAttribute.Email.AttributeName) { throw new ArgumentException(string.Format("Invalid attribute name, only {0} and {1} can be verified", CognitoAttribute.PhoneNumber, CognitoAttribute.Email), nameof(attributeName)); } try { await _cognitoClient.GetUserAttributeVerificationCodeAsync(new GetUserAttributeVerificationCodeRequest { AccessToken = user.SessionTokens.AccessToken, AttributeName = attributeName }, cancellationToken).ConfigureAwait(false); return IdentityResult.Success; } catch (AmazonCognitoIdentityProviderException e) { return IdentityResult.Failed(_errorDescribers.CognitoServiceError("Failed to get the Cognito User attribute verification code", e)); } } /// <summary> /// Verifies the confirmation <paramref name="code"/> for the specified <paramref name="user"/>, /// and the specified <paramref name="attributeName"/>, /// as an asynchronous operation. /// </summary> /// <param name="user">The user to verify the code for.</param> /// <param name="attributeName">The attribute to verify.</param> /// <param name="code">The verification code to check.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public virtual async Task<IdentityResult> VerifyUserAttributeAsync(TUser user, string attributeName, string code, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (attributeName != CognitoAttribute.PhoneNumber.AttributeName && attributeName != CognitoAttribute.Email.AttributeName) { throw new ArgumentException(string.Format("Invalid attribute name, only {0} and {1} can be verified", CognitoAttribute.PhoneNumber, CognitoAttribute.Email), nameof(attributeName)); } try { await _cognitoClient.VerifyUserAttributeAsync(new VerifyUserAttributeRequest { AccessToken = user.SessionTokens.AccessToken, AttributeName = attributeName, Code = code }, cancellationToken).ConfigureAwait(false); return IdentityResult.Success; } catch (AmazonCognitoIdentityProviderException e) { return IdentityResult.Failed(_errorDescribers.CognitoServiceError("Failed to verify the attribute for the Cognito User", e)); } } /// <summary> /// Internal method to get a user attribute value, while checking if this attribute is readable /// </summary> /// <param name="user">The user to retrieve the attribute for.</param> /// <param name="attributeName">The attribute to retrieve.</param> /// <returns></returns> private async Task<string> GetAttributeValueAsync(TUser user, string attributeName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user.Attributes == null) { throw new ArgumentException("user.Attributes must be initialized."); } var clientConfig = await _pool.GetUserPoolClientConfiguration().ConfigureAwait(false); if (!clientConfig.ReadAttributes.Contains(attributeName)) { throw new NotAuthorizedException(string.Format("Reading attribute {0} is not allowed by the user pool client configuration.", attributeName)); } // There is an edge case where an attribute might be there in the pool configuration, but not on the user profile if (user.Attributes.ContainsKey(attributeName)) { return user.Attributes[attributeName]; } else { return null; } } /// <summary> /// Internal method to get a user attribute value, while checking if this attribute is settable. /// </summary> /// <param name="user">The user to set the attribute for.</param> /// <param name="attributeName">The attribute name.</param> /// <param name="attributeValue">The new attribute value.</param> /// <returns></returns> private async Task SetAttributeValueAsync(TUser user, string attributeName, string attributeValue, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user.Attributes == null) { throw new ArgumentException("user.Attributes must be initialized."); } var clientConfig = await _pool.GetUserPoolClientConfiguration().ConfigureAwait(false); if (!clientConfig.WriteAttributes.Contains(attributeName)) { throw new NotAuthorizedException(string.Format("Writing to attribute {0} is not allowed by the user pool client configuration.", attributeName)); } user.Attributes[attributeName] = attributeValue; } #endregion #region IDisposable private bool disposed = false; protected virtual void Dispose(bool disposing) { if (disposed) return; disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
575
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.AspNetCore.Identity.Cognito.Exceptions; using Amazon.CognitoIdentityProvider; using Amazon.CognitoIdentityProvider.Model; using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; namespace Amazon.AspNetCore.Identity.Cognito { public partial class CognitoUserStore<TUser> : IUserClaimStore<TUser> where TUser : CognitoUser { /// <summary> /// Gets a list of <see cref="Claim"/>s to be belonging to the specified <paramref name="user"/> as an asynchronous operation. /// </summary> /// <param name="user">The role whose claims to retrieve.</param> /// <returns> /// A <see cref="Task{TResult}"/> that represents the result of the asynchronous query, a list of <see cref="Claim"/>s. /// </returns> public virtual async Task<IList<Claim>> GetClaimsAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } try { var details = await _cognitoClient.AdminGetUserAsync(new AdminGetUserRequest { Username = user.Username, UserPoolId = _pool.PoolID }, cancellationToken).ConfigureAwait(false); return details.UserAttributes.Select(att => new Claim(att.Name, att.Value)).ToList(); } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to retrieve Cognito User claims", e); } } /// <summary> /// Add claims to a user as an asynchronous operation. /// </summary> /// <param name="user">The user to add the claim to.</param> /// <param name="claims">The collection of <see cref="Claim"/>s to add.</param> /// <returns>The task object representing the asynchronous operation.</returns> public virtual async Task AddClaimsAsync(TUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (claims == null) { throw new ArgumentNullException(nameof(claims)); } if (claims.Any()) { try { await _cognitoClient.AdminUpdateUserAttributesAsync(new AdminUpdateUserAttributesRequest { UserAttributes = CreateAttributeList(claims.ToDictionary(claim => claim.Type, claim => claim.Value)), Username = user.Username, UserPoolId = _pool.PoolID }, cancellationToken).ConfigureAwait(false); } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to add a claim to the Cognito User", e); } } } /// <summary> /// Replaces the given <paramref name="claim"/> on the specified <paramref name="user"/> with the <paramref name="newClaim"/> /// </summary> /// <param name="user">The user to replace the claim on.</param> /// <param name="claim">The claim to replace.</param> /// <param name="newClaim">The new claim to replace the existing <paramref name="claim"/> with.</param> /// <returns>The task object representing the asynchronous operation.</returns> public Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); throw new NotSupportedException("Cognito does not support replacing claims. Call RemoveClaimsAsync() and AddClaimsAsync() instead."); } /// <summary> /// Removes the specified <paramref name="claims"/> from the given <paramref name="user"/>. /// </summary> /// <param name="user">The user to remove the specified <paramref name="claims"/> from.</param> /// <param name="claims">A collection of <see cref="Claim"/>s to remove.</param> /// <returns>The task object representing the asynchronous operation.</returns> public virtual async Task RemoveClaimsAsync(TUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (claims == null) { throw new ArgumentNullException(nameof(claims)); } var userClaims = await GetClaimsAsync(user, cancellationToken).ConfigureAwait(false); // Only removes the claims that the user actually have. var matchedClaims = userClaims.Select(claim => new { claim.Type, claim.Value }) .Intersect(claims.Select(claim => new { claim.Type, claim.Value })); if (matchedClaims.Any()) { try { await _cognitoClient.AdminDeleteUserAttributesAsync(new AdminDeleteUserAttributesRequest { UserAttributeNames = matchedClaims.Select(claim => claim.Type).ToList(), Username = user.Username, UserPoolId = _pool.PoolID }, cancellationToken).ConfigureAwait(false); } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to remove a claim from the Cognito User", e); } } } /// <summary> /// Returns a list of users who contain the specified <see cref="Claim"/>. /// </summary> /// <param name="claim">The claim to look for.</param> /// <returns> /// A <see cref="Task{TResult}"/> that represents the result of the asynchronous query, a list of <typeparamref name="TUser"/> who /// contain the specified claim. /// </returns> public async Task<IList<TUser>> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (claim == null) { throw new ArgumentNullException(nameof(claim)); } if (CognitoAttribute.FilterableAttributes.Contains(claim.Type)) { try { var response = await _cognitoClient.ListUsersAsync(new ListUsersRequest { Filter = claim.Type + "=\"" + claim.Value + "\"", UserPoolId = _pool.PoolID }, cancellationToken).ConfigureAwait(false); return response.Users.Select(user => _pool.GetUser(user.Username, user.UserStatus, user.Attributes.ToDictionary(att => att.Name, att => att.Value))).ToList() as IList<TUser>; } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to get the list of users for a specific claim", e); } } else { throw new NotSupportedException(String.Format("Retrieving the list of users with the claim type {0} is not supported", claim.Type)); } } } }
200
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.AspNetCore.Identity.Cognito.Exceptions; using Amazon.CognitoIdentityProvider; using Amazon.CognitoIdentityProvider.Model; using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Identity; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Amazon.AspNetCore.Identity.Cognito { public partial class CognitoUserStore<TUser> : IUserEmailStore<TUser> where TUser : CognitoUser { /// <summary> /// Gets the user, if any, associated with the specified, normalized email address. /// </summary> /// <param name="normalizedEmail">The normalized email address to return the user for.</param> /// <returns> /// The task object containing the results of the asynchronous lookup operation, the user if any associated with the specified normalized email address. /// </returns> public virtual async Task<TUser> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { var result = await _cognitoClient.ListUsersAsync(new ListUsersRequest { Filter = "email = \"" + normalizedEmail + "\"", UserPoolId = _pool.PoolID }, cancellationToken).ConfigureAwait(false); if (result.Users.Count > 0) { return _pool.GetUser(result.Users[0].Username, result.Users[0].UserStatus, result.Users[0].Attributes.ToDictionary(att => att.Name, att => att.Value)) as TUser; } } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to find the Cognito User by email", e); } return null; } public virtual async Task<string> GetEmailAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return await GetAttributeValueAsync(user, CognitoAttribute.Email.AttributeName, cancellationToken).ConfigureAwait(false); } public virtual async Task<bool> GetEmailConfirmedAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return String.Equals(await GetAttributeValueAsync(user, CognitoAttribute.EmailVerified.AttributeName, cancellationToken).ConfigureAwait(false), "true", StringComparison.InvariantCultureIgnoreCase); } public Task<string> GetNormalizedEmailAsync(TUser user, CancellationToken cancellationToken) { throw new NotSupportedException("Cognito does not support normalized emails."); } public virtual Task SetEmailAsync(TUser user, string email, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return SetAttributeValueAsync(user, CognitoAttribute.Email.AttributeName, email, cancellationToken); } public Task SetEmailConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken) { throw new NotSupportedException("Cognito does not allow updating the email_verified attribute. This attribute gets updated automatically upon email change or confirmation."); } public Task SetNormalizedEmailAsync(TUser user, string normalizedEmail, CancellationToken cancellationToken) { throw new NotSupportedException("Cognito does not support normalized emails."); } } }
101
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Identity; using System; using System.Threading; using System.Threading.Tasks; namespace Amazon.AspNetCore.Identity.Cognito { public partial class CognitoUserStore<TUser> : IUserPhoneNumberStore<TUser> where TUser : CognitoUser { public virtual async Task<string> GetPhoneNumberAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return await GetAttributeValueAsync(user, CognitoAttribute.PhoneNumber.AttributeName, cancellationToken).ConfigureAwait(false); } public virtual async Task<bool> GetPhoneNumberConfirmedAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return String.Equals(await GetAttributeValueAsync(user, CognitoAttribute.PhoneNumberVerified.AttributeName, cancellationToken).ConfigureAwait(false), "true", StringComparison.InvariantCultureIgnoreCase); } public virtual Task SetPhoneNumberAsync(TUser user, string phoneNumber, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return SetAttributeValueAsync(user, CognitoAttribute.PhoneNumber.AttributeName, phoneNumber, cancellationToken); } public Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken) { throw new NotSupportedException("Cognito does not allow updating the phone_verified attribute. This attribute gets updated automatically upon phone number change or confirmation."); } } }
53
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.AspNetCore.Identity.Cognito.Exceptions; using Amazon.CognitoIdentityProvider; using Amazon.CognitoIdentityProvider.Model; using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Amazon.AspNetCore.Identity.Cognito { public partial class CognitoUserStore<TUser> : IUserRoleStore<TUser> where TUser : CognitoUser { #region IUserStore /// <summary> /// Finds and returns a user, if any, who has the specified <paramref name="userId"/>. /// </summary> /// <param name="userId">The user ID to search for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the user matching the specified <paramref name="userId"/> if it exists. /// </returns> public virtual async Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { // The userId can be the userName, the email or the phone number depending on the User Pool login policy var user = await _pool.FindByIdAsync(userId).ConfigureAwait(false); return user as TUser; } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to find the Cognito User by Id", e); } } /// <summary> /// Returns the userId associated with the <paramref name="user"/>. /// </summary> /// <param name="user">The user to retrieve the id for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the userId belonging to the matching the specified <paramref name="userId"/>. /// </returns> public virtual Task<string> GetUserIdAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.FromResult(user.UserID); } /// <summary> /// Returns the UserName associated with the <paramref name="user"/>. /// </summary> /// <param name="user">The user to retrieve the UserName for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the UserName belonging to the matching the specified <paramref name="userId"/>. /// </returns> public virtual Task<string> GetUserNameAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.FromResult(user.Username); } /// <summary> /// Registers the specified <paramref name="user"/> in Cognito, /// as an asynchronous operation. /// </summary> /// <param name="user">The user to create.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> public virtual Task<IdentityResult> CreateAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return CreateAsync(user, null, cancellationToken); } /// <summary> /// Registers the specified <paramref name="user"/> in Cognito, /// as an asynchronous operation. Also submits the validation data to the pre sign-up lambda trigger. /// </summary> /// <param name="user">The user to create.</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 virtual async Task<IdentityResult> CreateAsync(TUser user, IDictionary<string, string> validationData, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { await _pool.AdminSignupAsync(user.UserID, user.Attributes, validationData).ConfigureAwait(false); return IdentityResult.Success; } catch (AmazonCognitoIdentityProviderException e) { return IdentityResult.Failed(_errorDescribers.CognitoServiceError("Failed to create the Cognito User", e)); } } /// <summary> /// Deletes the specified <paramref name="user"/> from the user store. /// </summary> /// <param name="user">The user to delete.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the update operation.</returns> public virtual async Task<IdentityResult> DeleteAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { await _cognitoClient.AdminDeleteUserAsync(new AdminDeleteUserRequest { Username = user.Username, UserPoolId = _pool.PoolID }, cancellationToken).ConfigureAwait(false); return IdentityResult.Success; } catch (AmazonCognitoIdentityProviderException e) { return IdentityResult.Failed(_errorDescribers.CognitoServiceError("Failed to delete the Cognito User", e)); } } /// <summary> /// Finds and returns a user, if any, who has the specified normalized user name. /// </summary> /// <param name="normalizedUserName">The normalized user name to search for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the user matching the specified <paramref name="normalizedUserName"/> if it exists. /// </returns> public virtual Task<TUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken) { return FindByIdAsync(normalizedUserName, cancellationToken); } public Task<string> GetNormalizedUserNameAsync(TUser user, CancellationToken cancellationToken) { throw new NotSupportedException("Cognito is case-sensitive and does not support normalized user name"); } public Task SetNormalizedUserNameAsync(TUser user, string normalizedName, CancellationToken cancellationToken) { throw new NotSupportedException("Cognito is case-sensitive and does not support normalized user name"); } public Task SetUserNameAsync(TUser user, string userName, CancellationToken cancellationToken) { throw new NotSupportedException("Cognito does not allow changing username, but the preferred_username attribute is allowed to change"); } /// <summary> /// Updates the specified <paramref name="user"/> attributes in the user store. /// </summary> /// <param name="user">The user to update attributes for.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> of the update operation.</returns> public virtual async Task<IdentityResult> UpdateAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } try { // Only update user writable attributes. var clientConfig = await _pool.GetUserPoolClientConfiguration().ConfigureAwait(false); var newValues = clientConfig.WriteAttributes .Where(key => user.Attributes.ContainsKey(key)) .ToDictionary(key => key, key => user.Attributes[key]); await _cognitoClient.AdminUpdateUserAttributesAsync(new AdminUpdateUserAttributesRequest { UserAttributes = CreateAttributeList(newValues), Username = user.Username, UserPoolId = _pool.PoolID }, cancellationToken).ConfigureAwait(false); return IdentityResult.Success; } catch (AmazonCognitoIdentityProviderException e) { return IdentityResult.Failed(_errorDescribers.CognitoServiceError("Failed to update the Cognito User", e)); } } /// <summary> /// Internal method to convert a dictionary of user attributes to a list of AttributeType /// </summary> /// <param name="attributeDict">Dictionary containing attributes of type string</param> /// <returns>Returns a List of AttributeType objects</returns> internal List<AttributeType> CreateAttributeList(IDictionary<string, string> attributeDict) { List<AttributeType> attributeList = new List<AttributeType>(); foreach (KeyValuePair<string, string> data in attributeDict) { AttributeType attribute = new AttributeType() { Name = data.Key, Value = data.Value }; attributeList.Add(attribute); } return attributeList; } #endregion #region IUserRoleStore /// <summary> /// Add the specified <paramref name="user"/> to the named role. /// </summary> /// <param name="user">The user to add to the named role.</param> /// <param name="roleName">The name of the role to add the user to.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task AddToRoleAsync(TUser user, string roleName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } try { return _cognitoClient.AdminAddUserToGroupAsync(new AdminAddUserToGroupRequest { GroupName = roleName, Username = user.Username, UserPoolId = _pool.PoolID }, cancellationToken); } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to add the Cognito User to a role", e); } } /// <summary> /// Remove the specified <paramref name="user"/> from the named role. /// </summary> /// <param name="user">The user to remove the named role from.</param> /// <param name="roleName">The name of the role to remove.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task RemoveFromRoleAsync(TUser user, string roleName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } try { return _cognitoClient.AdminRemoveUserFromGroupAsync(new AdminRemoveUserFromGroupRequest { GroupName = roleName, Username = user.Username, UserPoolId = _pool.PoolID }, cancellationToken); } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to remove the Cognito User from a role", e); } } /// <summary> /// Gets a list of role names the specified <paramref name="user"/> belongs to. /// </summary> /// <param name="user">The user whose role names to retrieve.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing a list of role names.</returns> public virtual async Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } try { // This calls retrieve ALL the groups var response = await _cognitoClient.AdminListGroupsForUserAsync(new AdminListGroupsForUserRequest { Username = user.Username, UserPoolId = _pool.PoolID }, cancellationToken).ConfigureAwait(false); return response.Groups.Select(group => group.GroupName).ToList(); } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to retrieve roles for the Cognito User", e); } } /// <summary> /// Returns a flag indicating whether the specified <paramref name="user"/> is a member of the given named role. /// </summary> /// <param name="user">The user whose role membership should be checked.</param> /// <param name="roleName">The name of the role to be checked.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing a flag indicating whether the specified <paramref name="user"/> is /// a member of the named role. /// </returns> public virtual async Task<bool> IsInRoleAsync(TUser user, string roleName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } var userRoles = await GetRolesAsync(user, cancellationToken).ConfigureAwait(false); return userRoles.Contains(roleName); } /// <summary> /// Returns a list of Users who are members of the named role. /// </summary> /// <param name="roleName">The name of the role whose membership should be returned.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing a list of users who are in the named role. /// </returns> public virtual async Task<IList<TUser>> GetUsersInRoleAsync(string roleName, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); try { // This calls retrieve ALL the user for a group var response = await _cognitoClient.ListUsersInGroupAsync(new ListUsersInGroupRequest { GroupName = roleName, UserPoolId = _pool.PoolID }, cancellationToken).ConfigureAwait(false); return response.Users.Select(user => _pool.GetUser(user.Username, user.UserStatus, user.Attributes.ToDictionary(att => att.Name, att => att.Value))).ToList() as IList<TUser>; } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to get the Cognito Users in a role", e); } } #endregion } }
378
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.AspNetCore.Identity.Cognito.Exceptions; using Amazon.CognitoIdentityProvider; using Amazon.CognitoIdentityProvider.Model; using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Amazon.AspNetCore.Identity.Cognito { public partial class CognitoUserStore<TUser> : IUserTwoFactorStore<TUser> where TUser : CognitoUser { /// <summary> /// Returns a flag indicating whether the specified <paramref name="user"/> has two factor authentication enabled or not, /// as an asynchronous operation. /// </summary> /// <param name="user">The user whose two factor authentication enabled status should be retrieved.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing a flag indicating whether the specified /// <paramref name="user"/> has two factor authentication enabled or not. /// </returns> public virtual async Task<bool> GetTwoFactorEnabledAsync(TUser user, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } var request = new AdminGetUserRequest { Username = user.Username, UserPoolId = _pool.PoolID }; try { var userSettings = await _cognitoClient.AdminGetUserAsync(request, cancellationToken).ConfigureAwait(false); return userSettings.MFAOptions.Count > 0; } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to retrieve 2FA settings for the Cognito User", e); } } /// <summary> /// Sets a flag indicating whether the specified <paramref name="user"/> has two factor authentication enabled or not, /// as an asynchronous operation. /// </summary> /// <param name="user">The user whose two factor authentication enabled status should be set.</param> /// <param name="enabled">A flag indicating whether the specified <paramref name="user"/> has two factor authentication enabled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual async Task SetTwoFactorEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } var request = new AdminSetUserSettingsRequest { Username = user.Username, UserPoolId = _pool.PoolID, MFAOptions = new List<MFAOptionType>() { new MFAOptionType() { AttributeName = CognitoAttribute.PhoneNumber.AttributeName, DeliveryMedium = enabled ? DeliveryMediumType.SMS : null // Undocumented SDK behavior: sending null disables SMS 2FA } } }; try { await _cognitoClient.AdminSetUserSettingsAsync(request, cancellationToken).ConfigureAwait(false); } catch (AmazonCognitoIdentityProviderException e) { throw new CognitoServiceException("Failed to set 2FA settings for the Cognito User", e); } } } }
105
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Amazon.AspNetCore.Identity.Cognito { /// <summary> /// Provides an abstraction for a store which manages Cognito accounts. /// This includes Cognito specific methods such has handling the auth workflow, /// Retrieving the user status or changing/reseting the password. /// </summary> /// <typeparam name="TUser">The type encapsulating a user.</typeparam> public interface IUserCognitoStore<TUser> : IDisposable where TUser : class { /// <summary> /// Checks if the <param name="user"> can log in with the specified password <paramref name="password"/>. /// </summary> /// <param name="user">The user try to log in with.</param> /// <param name="password">The password supplied for validation.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the AuthFlowResponse object linked to that authentication workflow.</returns> Task<AuthFlowResponse> StartValidatePasswordAsync(TUser user, string password, CancellationToken cancellationToken); /// <summary> /// Changes the password on the cognito account associated with the <paramref name="user"/>. /// </summary> /// <param name="user">The user to change the password for.</param> /// <param name="currentPassword">The current password of the user.</param> /// <param name="newPassword">The new passord for the user.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing a boolean set to true if changing the password was successful, false otherwise.</returns> Task<IdentityResult> ChangePasswordAsync(TUser user, string currentPassword, string newPassword, CancellationToken cancellationToken); /// <summary> /// Resets the <paramref name="user"/>'s password to the specified <paramref name="newPassword"/> after /// validating the given password reset <paramref name="token"/>. /// </summary> /// <param name="user">The user whose password should be reset.</param> /// <param name="token">The password reset token to verify.</param> /// <param name="newPassword">The new password to set if reset token verification succeeds.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> Task<IdentityResult> ChangePasswordWithTokenAsync(TUser user, string token, string newPassword, CancellationToken cancellationToken); /// <summary> /// Checks if the password needs to be changed for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user to check if the password needs to be changed.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing a boolean set to true if the password needs to be changed, false otherwise.</returns> Task<bool> IsPasswordChangeRequiredAsync(TUser user, CancellationToken cancellationToken); /// <summary> /// Checks if the password needs to be reset for the specified <paramref name="user"/>. /// </summary> /// <param name="user">The user to check if the password needs to be reset.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing a boolean set to true if the password needs to be reset, false otherwise.</returns> Task<bool> IsPasswordResetRequiredAsync(TUser user, CancellationToken cancellationToken); /// <summary> /// Resets the <paramref name="user"/>'s password and sends the confirmation token to the user /// via email or sms depending on the user pool policy. /// </summary> /// <param name="user">The user to reset the password for.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing a boolean set to true if the password was reset, false otherwise.</returns> Task<IdentityResult> ResetPasswordAsync(TUser user, CancellationToken cancellationToken); /// <summary> /// Registers the specified <paramref name="user"/> in Cognito with the given password, /// as an asynchronous operation. /// </summary> /// <param name="user">The user to create.</param> /// <param name="password">The password for the user to register with</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> Task<IdentityResult> CreateAsync(TUser user, string password, IDictionary<string, string> validationData, CancellationToken cancellationToken); /// <summary> /// Queries Cognito and returns the users in the pool. Optional filters can be applied on the users to retrieve based on their attributes. /// Providing an empty attributeFilterName parameter returns all the users in the pool. /// </summary> /// <param name="attributeFilterName"> The attribute name to filter your search on. You can only search for the following standard attributes: /// username (case-sensitive) /// email /// phone_number /// name /// given_name /// family_name /// preferred_username /// cognito:user_status (called Status in the Console) (case-insensitive) /// status (called Enabled in the Console) (case-sensitive) /// sub /// Custom attributes are not searchable. /// For more information, see Searching for Users Using the ListUsers API and Examples /// of Using the ListUsers API in the Amazon Cognito Developer Guide.</param> /// <param name="attributeFilterType"> The type of filter to apply: /// For an exact match, use = /// For a prefix ("starts with") match, use ^= /// </param> /// <param name="attributeFilterValue"> The filter value for the specified attribute.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing a IEnumerable of CognitoUser. /// </returns> Task<IEnumerable<CognitoUser>> GetUsersAsync(CognitoAttribute attributeFilterName, CognitoAttributeFilterType attributeFilterType, string attributeFilterValue, CancellationToken cancellationToken); /// <summary> /// Registers the specified <paramref name="user"/> in Cognito with the given password, /// as an asynchronous operation. Also submits the validation data to the pre sign-up lambda trigger. /// </summary> /// <param name="user">The user to create.</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> Task<IdentityResult> CreateAsync(TUser user, IDictionary<string, string> validationData, CancellationToken cancellationToken); /// <summary> /// Confirms the specified <paramref name="user"/> with the specified /// <paramref name="confirmationCode"/> they were sent by email or sms, /// as an asynchronous operation. /// When a new user is confirmed, the user's attribute through which the /// confirmation code was sent (email address or phone number) is marked as verified. /// If this attribute is also set to be used as an alias, then the user can sign in with /// that attribute (email address or phone number) instead of the username. /// </summary> /// <param name="user">The user to confirm.</param> /// <param name="confirmationCode">The confirmation code that was sent by email or sms.</param> /// <param name="forcedAliasCreation">If set to true, this resolves potential alias conflicts by marking the attribute email or phone number verified. /// If set to false and an alias conflict exists, then the user confirmation will fail.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> Task<IdentityResult> ConfirmSignUpAsync(TUser user, string confirmationCode, bool forcedAliasCreation, CancellationToken cancellationToken); /// <summary> /// Admin confirms the specified <paramref name="user"/>, regardless of the confirmation code /// as an asynchronous operation. /// </summary> /// <param name="user">The user to confirm.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> Task<IdentityResult> AdminConfirmSignUpAsync(TUser user, CancellationToken cancellationToken); /// <summary> /// Resends the account signup confirmation code for the specified <paramref name="user"/> /// as an asynchronous operation. /// </summary> /// <param name="user">The user to resend the account signup confirmation code for.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> Task<IdentityResult> ResendSignupConfirmationCodeAsync(TUser user, CancellationToken cancellationToken); /// <summary> /// Generates and sends a verification code for the specified <paramref name="user"/>, /// and the specified <paramref name="attributeName"/>, /// as an asynchronous operation. /// This operation requires a logged in user. /// </summary> /// <param name="user">The user to send the verification code to.</param> /// <param name="attributeName">The attribute to verify.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> Task<IdentityResult> GetUserAttributeVerificationCodeAsync(TUser user, string attributeName, CancellationToken cancellationToken); /// <summary> /// Verifies the confirmation <paramref name="code"/> for the specified <paramref name="user"/>, /// and the specified <paramref name="attributeName"/>, /// as an asynchronous operation. /// </summary> /// <param name="user">The user to verify the code for.</param> /// <param name="attributeName">The attribute to verify.</param> /// <param name="code">The verification code to check.</param> /// <returns> /// The <see cref="Task"/> that represents the asynchronous operation, containing the <see cref="IdentityResult"/> /// of the operation. /// </returns> Task<IdentityResult> VerifyUserAttributeAsync(TUser user, string attributeName, string code, CancellationToken cancellationToken); /// <summary> /// Checks if the <param name="user"> can log in with the specified 2fa code challenge <paramref name="code"/>. /// </summary> /// <param name="user">The user try to log in with.</param> /// <param name="code">The 2fa code to check</param> /// <param name="authWorkflowSessionId">The ongoing Cognito authentication workflow id.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation, containing the AuthFlowResponse object linked to that authentication workflow.</returns> Task<AuthFlowResponse> RespondToTwoFactorChallengeAsync(TUser user, string code, string authWorkflowSessionId, CancellationToken cancellationToken); } }
216
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; namespace Amazon.AspNetCore.Identity.Cognito.Exceptions { public class CognitoConfigurationException : Exception { /// <summary> /// Constructs an instance of CognitoConfigurationException /// </summary> /// <param name="message">The error message.</param> public CognitoConfigurationException(string message) : base(message) { } /// <summary> /// Constructs an instance of CognitoConfigurationException /// </summary> /// <param name="message">The error message.</param> /// <param name="innerException">The original exception.</param> public CognitoConfigurationException(string message, Exception innerException) : base(message, innerException) { } private CognitoConfigurationException() { } } }
42
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.CognitoIdentityProvider; using Microsoft.AspNetCore.Identity; using System; namespace Amazon.AspNetCore.Identity.Cognito.Exceptions { /// <summary> /// Service to enable Cognito specific errors for application facing identity errors. /// </summary> /// <remarks> /// These errors are returned to controllers and are generally used as display messages to end users. /// </remarks> public class CognitoIdentityErrorDescriber : IdentityErrorDescriber { /// <summary> /// Returns the <see cref="IdentityError"/> indicating a CognitoServiceError. /// </summary> /// <param name="failingOperationMessage">The message related to the operation that failed</param> /// <param name="exception">The exception</param> /// <returns>The default <see cref="IdentityError"/>.</returns> public IdentityError CognitoServiceError(string failingOperationMessage, AmazonCognitoIdentityProviderException exception) { return new IdentityError { Code = nameof(CognitoServiceError), Description = String.Format("{0} : {1}", failingOperationMessage, exception.Message) }; } } }
46
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; namespace Amazon.AspNetCore.Identity.Cognito.Exceptions { public class CognitoServiceException : Exception { private CognitoServiceException() { } private CognitoServiceException(string message) : base(message) { } /// <summary> /// Constructs an instance of CognitoServiceException /// </summary> /// <param name="message">The error message.</param> /// <param name="innerException">The original exception.</param> public CognitoServiceException(string message, Exception innerException) : base(message, innerException) { } } }
39
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ namespace Amazon.AspNetCore.Identity.Cognito.Extensions { public class AWSCognitoClientOptions { /// <summary> /// The User Pool client id. /// </summary> public string UserPoolClientId { get; set; } /// <summary> /// The User Pool client secret associated with the client id. /// </summary> public string UserPoolClientSecret { get; set; } /// <summary> /// The User Pool id associated with the client id. /// </summary> public string UserPoolId { get; set; } } }
36
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.AspNetCore.Identity.Cognito; using Amazon.AspNetCore.Identity.Cognito.Exceptions; using Amazon.AspNetCore.Identity.Cognito.Extensions; using Amazon.CognitoIdentityProvider; using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Configuration; using System; using System.Linq; using System.Reflection; namespace Microsoft.Extensions.DependencyInjection { public static class CognitoServiceCollectionExtensions { public static IServiceCollection AddCognitoIdentity(this IServiceCollection services, Action<IdentityOptions> identityOptions = null, string prefix = null) { services.InjectCognitoUser<CognitoUser>(identityOptions); services.TryAddAWSService<IAmazonCognitoIdentityProvider>(); services.TryAddCognitoUserPool(); return services; } private static IServiceCollection InjectCognitoUser<TUser>(this IServiceCollection services, Action<IdentityOptions> identityOptions = null) where TUser : CognitoUser { if (identityOptions != null) { services.Configure(identityOptions); services.AddIdentity<CognitoUser, CognitoRole>() .AddDefaultTokenProviders() .AddPasswordValidator<CognitoPasswordValidator>(); } else { services.AddIdentity<CognitoUser, CognitoRole>() .AddDefaultTokenProviders() .AddPasswordValidator<CognitoPasswordValidator>(); var passwordValidators = services.Where(s => s.ServiceType.Equals(typeof(IPasswordValidator<CognitoUser>))); foreach (var validator in passwordValidators.ToArray()) { if (Equals(validator.ImplementationType, typeof(PasswordValidator<CognitoUser>))) { services.Remove(validator); } } } // Overrides the managers/stores with Cognito specific ones. services.AddScoped<UserManager<TUser>, CognitoUserManager<TUser>>(); services.AddScoped<SignInManager<TUser>, CognitoSignInManager<TUser>>(); services.AddScoped<IUserStore<TUser>, CognitoUserStore<TUser>>(); services.AddScoped<IRoleStore<CognitoRole>, CognitoRoleStore<CognitoRole>>(); services.AddScoped<IUserClaimStore<TUser>, CognitoUserStore<TUser>>(); services.AddScoped<IUserClaimsPrincipalFactory<TUser>, CognitoUserClaimsPrincipalFactory<TUser>>(); services.AddSingleton<CognitoKeyNormalizer, CognitoKeyNormalizer>(); services.AddSingleton<IdentityErrorDescriber, CognitoIdentityErrorDescriber>(); services.AddHttpContextAccessor(); return services; } private static IServiceCollection TryAddCognitoUserPool(this IServiceCollection services, ServiceLifetime lifetime = ServiceLifetime.Singleton) { if (!services.Any(x => x.ServiceType == typeof(CognitoUserPool))) { Func<IServiceProvider, CognitoUserPool> factory = CognitoUserPoolFactory.CreateUserPoolClient; var descriptor = new ServiceDescriptor(typeof(CognitoUserPool), factory, lifetime); services.Add(descriptor); } return services; } } internal static class CognitoUserPoolFactory { private const string MissingConfigurationExceptionMessage = "No IConfiguration object instance was found in the service collection. Could not instanciate a CognitoUserPool object."; private const string UserAgentHeader = "User-Agent"; private static string _assemblyFileVersion = "Unknown"; public static CognitoUserPool CreateUserPoolClient(IServiceProvider provider) { // Checks if AWSCognitoClientOptions are already set up var options = provider.GetService<AWSCognitoClientOptions>(); if (options == null) { var configuration = provider.GetService<IConfiguration>(); if (configuration != null) { options = configuration.GetAWSCognitoClientOptions(); } else { throw new CognitoConfigurationException(MissingConfigurationExceptionMessage); } } _assemblyFileVersion = GetAssemblyFileVersion(); var cognitoClient = provider.GetService<IAmazonCognitoIdentityProvider>(); if (cognitoClient is AmazonCognitoIdentityProviderClient eventProvider) { eventProvider.BeforeRequestEvent += ServiceClientBeforeRequestEvent; } var cognitoPool = new CognitoUserPool(options.UserPoolId, options.UserPoolClientId, cognitoClient, options.UserPoolClientSecret); return cognitoPool; } private static void ServiceClientBeforeRequestEvent(object sender, Amazon.Runtime.RequestEventArgs e) { Amazon.Runtime.WebServiceRequestEventArgs args = e as Amazon.Runtime.WebServiceRequestEventArgs; if (args == null || !args.Headers.ContainsKey(UserAgentHeader)) return; args.Headers[UserAgentHeader] = args.Headers[UserAgentHeader] + " CognitoASPNETCoreIdentityProvider/" + _assemblyFileVersion; } private static string GetAssemblyFileVersion() { var assembly = typeof(CognitoServiceCollectionExtensions).GetTypeInfo().Assembly; AssemblyFileVersionAttribute attribute = assembly.GetCustomAttribute(typeof(AssemblyFileVersionAttribute)) as AssemblyFileVersionAttribute; return attribute == null ? "Unknown" : attribute.Version; } } }
143
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.AspNetCore.Identity.Cognito.Exceptions; using Amazon.AspNetCore.Identity.Cognito.Extensions; namespace Microsoft.Extensions.Configuration { public static class ConfigurationExtensions { /// <summary> /// The default section where settings are read from the IConfiguration object. This is set to "AWS". /// </summary> public const string DEFAULT_CONFIG_SECTION = "AWS"; private const string ConfigurationClientIdKey = "UserPoolClientId"; private const string ConfigurationClientSecretKey = "UserPoolClientSecret"; private const string ConfigurationUserPoolIdKey = "UserPoolId"; private const string MissingKeyExceptionMessage = "The {0} key/value pair is missing or empty in the IConfiguration instance"; /// <summary> /// Constructs an AWSCognitoClientOptions class with the options specifed in the "AWS" section in the IConfiguration object. /// </summary> /// <param name="config">The IConfiguration instance</param> /// <returns>The AWSCognitoClientOptions containing the cognito secrets.</returns> public static AWSCognitoClientOptions GetAWSCognitoClientOptions(this IConfiguration config) { return GetAWSCognitoClientOptions(config, DEFAULT_CONFIG_SECTION); } public static AWSCognitoClientOptions GetAWSCognitoClientOptions(this IConfiguration config, string configSection) { var options = new AWSCognitoClientOptions(); IConfiguration section; if (string.IsNullOrEmpty(configSection)) section = config; else section = config.GetSection(configSection); if (section == null) return options; options.UserPoolClientId = GetConfigurationValue(section, ConfigurationClientIdKey); options.UserPoolClientSecret = GetConfigurationValue(section, ConfigurationClientSecretKey, true); options.UserPoolId = GetConfigurationValue(section, ConfigurationUserPoolIdKey); return options; } private static string GetConfigurationValue(IConfiguration section, string configurationKey, bool isOptional = false) { if (!string.IsNullOrEmpty(section[configurationKey]) || isOptional) { return section[configurationKey]; } throw new CognitoConfigurationException(string.Format(MissingKeyExceptionMessage, configurationKey)); } } }
75
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.CognitoIdentityProvider; using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Identity; using Moq; using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using Xunit; namespace Amazon.AspNetCore.Identity.Cognito.Tests { public class CognitoSigninManagerTests : ManagerTestBase { private CognitoSignInManager<CognitoUser> signinManager; private Mock<CognitoUserManager<CognitoUser>> userManagerMock; public CognitoSigninManagerTests() : base() { userManagerMock = new Mock<CognitoUserManager<CognitoUser>>(userStoreMock.Object, null, null, null, null, null, null, null, null, contextAccessorMock.Object); claimsFactoryMock = new Mock<CognitoUserClaimsPrincipalFactory<CognitoUser>>(userManagerMock.Object, optionsAccessorMock.Object); signinManager = new CognitoSignInManager<CognitoUser>(userManagerMock.Object, contextAccessorMock.Object, claimsFactoryMock.Object, optionsAccessorMock.Object, loggerSigninManagerMock.Object, schemesMock.Object, userConfirmationMock.Object); } [Fact] public async void Test_GivenAnUnknownUser_WhenPasswordSignIn_ThenReturnSigninResultFailed() { var signinResult = SignInResult.Failed; CognitoUser user = null; userManagerMock.Setup(mock => mock.FindByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(user)).Verifiable(); var output = await signinManager.PasswordSignInAsync("userId", "password", true, false).ConfigureAwait(false); Assert.Equal(signinResult, output); userManagerMock.Verify(); } [Fact] public async void Test_GivenAUserWithWrongPassword_WhenPasswordSignIn_ThenReturnSigninResultFailed() { AuthFlowResponse authFlowResponse = null; bool isPasswordChangeRequired = false; var signinResult = SignInResult.Failed; userManagerMock.Setup(mock => mock.FindByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(GetCognitoUser())).Verifiable(); userManagerMock.Setup(mock => mock.CheckPasswordAsync(It.IsAny<CognitoUser>(), It.IsAny<string>())).Returns(Task.FromResult(authFlowResponse)).Verifiable(); userManagerMock.Setup(mock => mock.IsPasswordChangeRequiredAsync(It.IsAny<CognitoUser>())).Returns(Task.FromResult(isPasswordChangeRequired)).Verifiable(); var output = await signinManager.PasswordSignInAsync("userId", "password", true, false).ConfigureAwait(false); Assert.Equal(signinResult, output); userManagerMock.Verify(); } [Fact] public async void Test_GivenAUserWithNo2FA_WhenPasswordSignIn_ThenReturnSigninResultSuccess() { var cognitoUser = GetCognitoUser(); var authFlowResponse = new AuthFlowResponse("sessionId", null, null, null, null); bool isPasswordChangeRequired = false; var signinResult = SignInResult.Success; userManagerMock.Setup(mock => mock.FindByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(cognitoUser)).Verifiable(); userManagerMock.Setup(mock => mock.IsPasswordChangeRequiredAsync(It.IsAny<CognitoUser>())).Returns(Task.FromResult(isPasswordChangeRequired)).Verifiable(); userManagerMock.Setup(mock => mock.CheckPasswordAsync(It.IsAny<CognitoUser>(), It.IsAny<string>())) .Returns(Task.FromResult(authFlowResponse)) .Callback(() => cognitoUser.SessionTokens = new CognitoUserSession("idToken", "accessToken", "refreshToken", DateTime.Now, DateTime.Now.AddDays(1))).Verifiable(); userManagerMock.Setup(mock => mock.GetClaimsAsync(It.IsAny<CognitoUser>())).Returns(Task.FromResult(new List<Claim>() as IList<Claim>)).Verifiable(); userManagerMock.Setup(mock => mock.GetRolesAsync(It.IsAny<CognitoUser>())).Returns(Task.FromResult(new List<string>() as IList<string>)).Verifiable(); var context = MockUtils.MockContext(cognitoUser, IdentityConstants.TwoFactorUserIdScheme); contextAccessorMock.Setup(a => a.HttpContext).Returns(context).Verifiable(); var output = await signinManager.PasswordSignInAsync("userId", "password", true, false).ConfigureAwait(false); Assert.Equal(signinResult, output); userManagerMock.Verify(); contextAccessorMock.Verify(); } [Fact] public async void Test_GivenAUserWithPasswordChangeRequired_WhenPasswordSignIn_ThenReturnSigninResultPassowrdChangeRequired() { bool isPasswordChangeRequired = true; var signinResult = CognitoSignInResult.PasswordChangeRequired; userManagerMock.Setup(mock => mock.FindByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(GetCognitoUser())).Verifiable(); userManagerMock.Setup(mock => mock.IsPasswordChangeRequiredAsync(It.IsAny<CognitoUser>())).Returns(Task.FromResult(isPasswordChangeRequired)).Verifiable(); var output = await signinManager.PasswordSignInAsync("userId", "password", true, false).ConfigureAwait(false); Assert.Equal(signinResult, output); userManagerMock.Verify(); } [Fact] public async void Test_GivenAUserWithPasswordResetRequired_WhenPasswordSignIn_ThenReturnSigninResultPassowrdResetRequired() { bool isPasswordResetRequired = true; var signinResult = CognitoSignInResult.PasswordResetRequired; userManagerMock.Setup(mock => mock.FindByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(GetCognitoUser())).Verifiable(); userManagerMock.Setup(mock => mock.IsPasswordResetRequiredAsync(It.IsAny<CognitoUser>())).Returns(Task.FromResult(isPasswordResetRequired)).Verifiable(); var output = await signinManager.PasswordSignInAsync("userId", "password", true, false).ConfigureAwait(false); Assert.Equal(signinResult, output); userManagerMock.Verify(); } [Fact] public async void Test_GivenAUserWith2FA_WhenPasswordSignIn_ThenReturnSigninResultTwoFactorRequired() { var cognitoUser = GetCognitoUser(); bool isPasswordChangeRequired = false; var signinResult = SignInResult.TwoFactorRequired; var authFlowResponse = new AuthFlowResponse("2FASESSIONID", null, ChallengeNameType.SMS_MFA, null, null); userManagerMock.Setup(mock => mock.FindByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(cognitoUser)); userManagerMock.Setup(mock => mock.CheckPasswordAsync(It.IsAny<CognitoUser>(), It.IsAny<string>())).Returns(Task.FromResult(authFlowResponse)); userManagerMock.Setup(mock => mock.IsPasswordChangeRequiredAsync(It.IsAny<CognitoUser>())).Returns(Task.FromResult(isPasswordChangeRequired)); var context = MockUtils.MockContext(cognitoUser, IdentityConstants.TwoFactorUserIdScheme); contextAccessorMock.Setup(a => a.HttpContext).Returns(context).Verifiable(); var output = await signinManager.PasswordSignInAsync("userId", "password", true, false).ConfigureAwait(false); Assert.Equal(signinResult, output); contextAccessorMock.Verify(); } [Fact] public async void Test_GivenAUserWith2FA_WhenRespondToTwoFactorChallengeWithCorrectCode_ThenReturnSigninResultSuccess() { var cognitoUser = GetCognitoUser(); var context = MockUtils.MockContext(cognitoUser, IdentityConstants.TwoFactorUserIdScheme); contextAccessorMock.Setup(a => a.HttpContext).Returns(context).Verifiable(); var authFlowResponse = new AuthFlowResponse("sessionId", null, ChallengeNameType.SMS_MFA, null, null); userManagerMock.Setup(mock => mock.FindByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(cognitoUser)).Verifiable(); userManagerMock.Setup(mock => mock.RespondToTwoFactorChallengeAsync(It.IsAny<CognitoUser>(), It.IsAny<string>(), It.IsAny<ChallengeNameType>(), It.IsAny<string>())) .Returns(Task.FromResult(authFlowResponse)) .Callback(() => cognitoUser.SessionTokens = new CognitoUserSession("idToken", "accessToken", "refreshToken", DateTime.Now, DateTime.Now.AddDays(1))).Verifiable(); userManagerMock.Setup(mock => mock.GetClaimsAsync(It.IsAny<CognitoUser>())).Returns(Task.FromResult(new List<Claim>() as IList<Claim>)).Verifiable(); userManagerMock.Setup(mock => mock.GetRolesAsync(It.IsAny<CognitoUser>())).Returns(Task.FromResult(new List<string>() as IList<string>)).Verifiable(); var output = await signinManager.RespondToTwoFactorChallengeAsync("2FACODE", true, false).ConfigureAwait(false); Assert.Equal(SignInResult.Success, output); contextAccessorMock.Verify(); userManagerMock.Verify(); } [Fact] public async void Test_GivenAUserWith2FA_WhenRespondToTwoFactorChallengeWithWrongCode_ThenReturnSigninResultFailed() { var cognitoUser = GetCognitoUser(); var context = MockUtils.MockContext(cognitoUser, IdentityConstants.TwoFactorUserIdScheme); contextAccessorMock.Setup(a => a.HttpContext).Returns(context).Verifiable(); AuthFlowResponse authFlowResponse = null; userManagerMock.Setup(mock => mock.FindByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(cognitoUser)).Verifiable(); userManagerMock.Setup(mock => mock.RespondToTwoFactorChallengeAsync(It.IsAny<CognitoUser>(), It.IsAny<string>(), It.IsAny<ChallengeNameType>(), It.IsAny<string>())) .Returns(Task.FromResult(authFlowResponse)).Verifiable(); var output = await signinManager.RespondToTwoFactorChallengeAsync("2FACODE", true, false).ConfigureAwait(false); Assert.Equal(SignInResult.Failed, output); contextAccessorMock.Verify(); userManagerMock.Verify(); } [Fact] public async void Test_GivenAUserSignedInWith2FAContext_WhenGetTwoFactorAuthenticationUser_ThenTheUserIsRetrieved() { var cognitoUser = GetCognitoUser(); var context = MockUtils.MockContext(cognitoUser, IdentityConstants.TwoFactorUserIdScheme); contextAccessorMock.Setup(a => a.HttpContext).Returns(context).Verifiable(); userManagerMock.Setup(mock => mock.FindByIdAsync(It.IsAny<string>())).Returns(Task.FromResult(cognitoUser)).Verifiable(); var output = await signinManager.GetTwoFactorAuthenticationUserAsync().ConfigureAwait(false); Assert.Equal(cognitoUser, output); contextAccessorMock.Verify(); userManagerMock.Verify(); } #region ExceptionTests [Fact] public async void Test_GivenUserIdAndLockoutActivated_WhenPasswordSignIn_ThenThrowsNotSupportedException() { var ex = await Assert.ThrowsAsync<NotSupportedException>(() => signinManager.PasswordSignInAsync("userId", "password", true, lockoutOnFailure: true)).ConfigureAwait(false); Assert.Equal("Lockout is not enabled for the CognitoUserManager.", ex.Message); } [Fact] public async void Test_GivenUserAndLockoutActivated_WhenPasswordSignIn_ThenThrowsNotSupportedException() { var cognitoUser = new CognitoUser("userId", "clientId", cognitoPoolMock.Object, cognitoClientMock.Object); var ex = await Assert.ThrowsAsync<NotSupportedException>(() => signinManager.PasswordSignInAsync(cognitoUser, "password", true, lockoutOnFailure: true)).ConfigureAwait(false); Assert.Equal("Lockout is not enabled for the CognitoUserManager.", ex.Message); } [Fact] public async void Test_GivenUserAndLockoutActivated_WhenCheckPasswordSignIn_ThenThrowsNotSupportedException() { var cognitoUser = new CognitoUser("userId", "clientId", cognitoPoolMock.Object, cognitoClientMock.Object); var ex = await Assert.ThrowsAsync<NotSupportedException>(() => signinManager.CheckPasswordSignInAsync(cognitoUser, "password", lockoutOnFailure: true)).ConfigureAwait(false); Assert.Equal("Lockout is not enabled for the CognitoUserManager.", ex.Message); } [Fact] public async void Test_GivenNullUser_WhenCheckPasswordSignIn_ThenThrowsArgumentNullException() { await Assert.ThrowsAsync<ArgumentNullException>(() => signinManager.CheckPasswordSignInAsync(null, "password", false)).ConfigureAwait(false); } [Fact] public async void Test_GivenNullUser_WhenPasswordSignIn_ThenThrowsArgumentNullException() { CognitoUser user = null; await Assert.ThrowsAsync<ArgumentNullException>(() => signinManager.PasswordSignInAsync(user, "password", false, false)).ConfigureAwait(false); } #endregion } }
239
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.CognitoIdentityProvider; using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Identity; using Moq; using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Amazon.AspNetCore.Identity.Cognito.Tests { public class CognitoUserManagerTests : ManagerTestBase { private CognitoUserManager<CognitoUser> userManager; public CognitoUserManagerTests() : base() { userManager = new CognitoUserManager<CognitoUser>(userStoreMock.Object, optionsAccessorMock.Object, passwordHasherMock.Object, new List<IUserValidator<CognitoUser>>() { userValidatorsMock.Object }, new List<IPasswordValidator<CognitoUser>>() { passwordValidatorsMock.Object }, keyNormalizer, errorsMock.Object, servicesMock.Object, loggerUserManagerMock.Object, contextAccessorMock.Object); } [Fact] public async void Test_GivenAUser_WhenCheckPassword_ThenResponseIsNotAltered() { var authFlowResponse = new AuthFlowResponse("sessionId", null, null, null, null); userStoreMock.Setup(mock => mock.StartValidatePasswordAsync(It.IsAny<CognitoUser>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(authFlowResponse)).Verifiable(); var output = await userManager.CheckPasswordAsync(GetCognitoUser(), "password").ConfigureAwait(false); Assert.Equal(authFlowResponse, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenRespondToTwoFactorChallenge_ThenResponseIsNotAltered() { var authFlowResponse = new AuthFlowResponse("sessionId", null, ChallengeNameType.SMS_MFA, null, null); userStoreMock.Setup(mock => mock.RespondToTwoFactorChallengeAsync(It.IsAny<CognitoUser>(), It.IsAny<string>(), It.IsAny<ChallengeNameType>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(authFlowResponse)).Verifiable(); var output = await userManager.RespondToTwoFactorChallengeAsync(GetCognitoUser(), "2FACODE", "SessionId").ConfigureAwait(false); Assert.Equal(authFlowResponse, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenSetTwoFactorEnabled_ThenReturnIdentityResultSuccess() { var output = await userManager.SetTwoFactorEnabledAsync(GetCognitoUser(), true).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenChangePassword_ThenResponseIsNotAltered() { userStoreMock.Setup(mock => mock.ChangePasswordAsync(It.IsAny<CognitoUser>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.ChangePasswordAsync(GetCognitoUser(), "old", "new").ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenIsPasswordChangeRequired_ThenResponseIsNotAltered() { userStoreMock.Setup(mock => mock.IsPasswordChangeRequiredAsync(It.IsAny<CognitoUser>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(true)).Verifiable(); var output = await userManager.IsPasswordChangeRequiredAsync(GetCognitoUser()).ConfigureAwait(false); Assert.True(output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUserAndNewPassword_WhenResetPassword_ThenResponseIsNotAltered() { userStoreMock.Setup(mock => mock.ChangePasswordWithTokenAsync(It.IsAny<CognitoUser>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.ResetPasswordAsync(GetCognitoUser(), "token", "newPassword").ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenSendEmailOrPhoneConfirmationToken_ThenResponseIsNotAltered() { var cognitoUser = GetCognitoUser(); userStoreMock.Setup(mock => mock.GetUserAttributeVerificationCodeAsync(It.IsAny<CognitoUser>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.SendEmailConfirmationTokenAsync(cognitoUser).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); output = await userManager.SendPhoneConfirmationTokenAsync(cognitoUser).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenCreate_ThenResponseIsNotAltered() { var cognitoUser = GetCognitoUser(); userStoreMock.Setup(mock => mock.CreateAsync(It.IsAny<CognitoUser>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); userStoreMock.Setup(mock => mock.CreateAsync(It.IsAny<CognitoUser>(), It.IsAny<string>(), It.IsAny<IDictionary<string, string>>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); passwordValidatorsMock.Setup(mock => mock.ValidateAsync(It.IsAny<CognitoUserManager<CognitoUser>>(), It.IsAny<CognitoUser>(), It.IsAny<string>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.CreateAsync(cognitoUser).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); output = await userManager.CreateAsync(cognitoUser, "password").ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenResetPassword_ThenResponseIsNotAltered() { userStoreMock.Setup(mock => mock.ResetPasswordAsync(It.IsAny<CognitoUser>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.ResetPasswordAsync(GetCognitoUser()).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenConfirmEmailOrPhoneNumber_ThenResponseIsNotAltered() { var cognitoUser = GetCognitoUser(); userStoreMock.Setup(mock => mock.VerifyUserAttributeAsync(It.IsAny<CognitoUser>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.ConfirmEmailAsync(cognitoUser, "code").ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); output = await userManager.ConfirmPhoneNumberAsync(cognitoUser, "code").ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenConfirmSignUp_ThenResponseIsNotAltered() { userStoreMock.Setup(mock => mock.ConfirmSignUpAsync(It.IsAny<CognitoUser>(), It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.ConfirmSignUpAsync(GetCognitoUser(), "code", true).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenAdminConfirmSignUp_ThenResponseIsNotAltered() { userStoreMock.Setup(mock => mock.AdminConfirmSignUpAsync(It.IsAny<CognitoUser>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.AdminConfirmSignUpAsync(GetCognitoUser()).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenResendSignupConfirmationCode_ThenResponseIsNotAltered() { userStoreMock.Setup(mock => mock.ResendSignupConfirmationCodeAsync(It.IsAny<CognitoUser>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.ResendSignupConfirmationCodeAsync(GetCognitoUser()).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenSetPhoneNumber_ThenResponseIsNotAltered() { userStoreMock.Setup(mock => mock.SetPhoneNumberAsync(It.IsAny<CognitoUser>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(0)).Verifiable(); userStoreMock.Setup(mock => mock.UpdateAsync(It.IsAny<CognitoUser>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.SetPhoneNumberAsync(GetCognitoUser(), "+1234567890").ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenSetEmail_ThenResponseIsNotAltered() { userStoreMock.Setup(mock => mock.SetEmailAsync(It.IsAny<CognitoUser>(), It.IsAny<string>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(0)).Verifiable(); userStoreMock.Setup(mock => mock.UpdateAsync(It.IsAny<CognitoUser>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.SetEmailAsync(GetCognitoUser(), "[email protected]").ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivennUser_WhenUpdateUser_ThenResponseIsNotAltered() { userStoreMock.Setup(mock => mock.UpdateAsync(It.IsAny<CognitoUser>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.UpdateAsync(GetCognitoUser()).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenAddClaims_ThenResponseIsNotAltered() { userStoreMock.Setup(mock => mock.AddClaimsAsync(It.IsAny<CognitoUser>(), It.IsAny<IEnumerable<Claim>>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.AddClaimsAsync(GetCognitoUser(), new List<Claim>()).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenRemoveClaims_ThenResponseIsNotAltered() { userStoreMock.Setup(mock => mock.RemoveClaimsAsync(It.IsAny<CognitoUser>(), It.IsAny<IEnumerable<Claim>>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(IdentityResult.Success)).Verifiable(); var output = await userManager.RemoveClaimsAsync(GetCognitoUser(), new List<Claim>()).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); userStoreMock.Verify(); } [Fact] public async void Test_GivenAListOfUsers_WhenGetUsers_ThenResponseIsNotAltered() { var user1 = new CognitoUser("userId1", "clientId", cognitoPoolMock.Object, cognitoClientMock.Object); var user2 = new CognitoUser("userId2", "clientId", cognitoPoolMock.Object, cognitoClientMock.Object); var user3 = new CognitoUser("userId3", "clientId", cognitoPoolMock.Object, cognitoClientMock.Object); IEnumerable<CognitoUser> users = new List<CognitoUser>() { user1, user2, user3 }; userStoreMock.Setup(mock => mock.GetUsersAsync(null, null, "", It.IsAny<CancellationToken>())).Returns(Task.FromResult(users)).Verifiable(); var output = await userManager.GetUsersAsync().ConfigureAwait(false); Assert.Equal(users, output); userStoreMock.Verify(); } #region ExceptionTests [Fact] public async void Test_GivenANullUser_WhenCheckPassword_ThenThrowsArgumentNullException() { await Assert.ThrowsAsync<ArgumentNullException>(() => userManager.CheckPasswordAsync(null, "password")).ConfigureAwait(false); } [Fact] public async void Test_GivenANullUser_WhenRespondToTwoFactorChallenge_ThenThrowsArgumentNullException() { await Assert.ThrowsAsync<ArgumentNullException>(() => userManager.RespondToTwoFactorChallengeAsync(null, "2FACODE", "SessionId")).ConfigureAwait(false); } [Fact] public async void Test_GivenANullUser_WhenSetTwoFactorEnabled_ThenThrowsArgumentNullException() { await Assert.ThrowsAsync<ArgumentNullException>(() => userManager.SetTwoFactorEnabledAsync(null, true)).ConfigureAwait(false); } [Fact] public async void Test_GivenANullUser_WhenChangePassword_ThenThrowsArgumentNullException() { await Assert.ThrowsAsync<ArgumentNullException>(() => userManager.ChangePasswordAsync(null, "old", "new")).ConfigureAwait(false); } [Fact] public async void Test_GivenANullUser_WhenResetPassword_ThenThrowsArgumentNullException() { await Assert.ThrowsAsync<ArgumentNullException>(() => userManager.ResetPasswordAsync(null)).ConfigureAwait(false); } [Fact] public async void Test_GivenANullUser_WhenUpdate_ThenThrowsArgumentNullException() { await Assert.ThrowsAsync<ArgumentNullException>(() => userManager.UpdateAsync(null)).ConfigureAwait(false); } [Fact] public async void Test_GivenANullUser_WhenAddClaims_ThenThrowsArgumentNullException() { await Assert.ThrowsAsync<ArgumentNullException>(() => userManager.AddClaimsAsync(null, new List<Claim>())).ConfigureAwait(false); } [Fact] public async void Test_GivenAUserAndNullListOfClaim_WhenAddClaims_ThenThrowsArgumentNullException() { await Assert.ThrowsAsync<ArgumentNullException>(() => userManager.AddClaimsAsync(GetCognitoUser(), null)).ConfigureAwait(false); } [Fact] public async void Test_GivenANullUser_WhenRemoveClaims_ThenThrowsArgumentNullException() { await Assert.ThrowsAsync<ArgumentNullException>(() => userManager.RemoveClaimsAsync(null, new List<Claim>())).ConfigureAwait(false); } [Fact] public async void Test_GivenAUserAndNullListOfClaim_WhenRemoveClaims_ThenThrowsArgumentNullException() { await Assert.ThrowsAsync<ArgumentNullException>(() => userManager.RemoveClaimsAsync(GetCognitoUser(), null)).ConfigureAwait(false); } [Fact] public async void Test_GivenAUser_WhenGenerateEmailConfirmationToken_ThenThrowsANotSupportedException() { await Assert.ThrowsAsync<NotSupportedException>(() => userManager.GenerateEmailConfirmationTokenAsync(null)).ConfigureAwait(false); } [Fact] public async void Test_GivenAUser_WhenGenerateChangePhoneNumberToken_ThenThrowsANotSupportedException() { await Assert.ThrowsAsync<NotSupportedException>(() => userManager.GenerateChangePhoneNumberTokenAsync(null, null)).ConfigureAwait(false); } [Fact] public async void Test_GivenAUser_WhenChangeEmail_ThenThrowsANotSupportedException() { await Assert.ThrowsAsync<NotSupportedException>(() => userManager.ChangeEmailAsync(null, null, null)).ConfigureAwait(false); } [Fact] public void Test_GivenAListOfUsers_WhenCallingUsersProperty_ThenThrowsANotSupportedException() { Assert.Throws<NotSupportedException>(() => userManager.Users); } #endregion } }
331
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.CognitoIdentityProvider.Model; using Moq; using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Amazon.AspNetCore.Identity.Cognito.Tests { public partial class CognitoUserStoreTests { private AdminGetUserResponse GET_USER_RESPONSE = new AdminGetUserResponse { UserAttributes = new List<AttributeType>() { new AttributeType() { Name = "Name1", Value = "Value1" }, new AttributeType() { Name = "Name2", Value = "Value2" }, new AttributeType() { Name = "Name2", Value = "Value2" } } }; [Fact] public async void Test_GivenAUser_WhenGetClaims_ThenTheListOfClaimsIsRetrieved() { _cognitoClientMock.Setup(mock => mock.AdminGetUserAsync(It.IsAny<AdminGetUserRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(GET_USER_RESPONSE)).Verifiable(); var output = await _store.GetClaimsAsync(_userMock.Object, CancellationToken.None).ConfigureAwait(false); Assert.Equal(GET_USER_RESPONSE.UserAttributes.Count, output.Count); Assert.Equal(GET_USER_RESPONSE.UserAttributes[2].Name, output[2].Type); Assert.Equal(GET_USER_RESPONSE.UserAttributes[1].Value, output[1].Value); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenAddClaimsWithPopulatedListOfClaims_ThenAdminUpdateUserAttributesIsCalled() { var claims = new List<Claim>() { new Claim("Name1", "Value1") }; _cognitoClientMock.Setup(mock => mock.AdminUpdateUserAttributesAsync(It.IsAny<AdminUpdateUserAttributesRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new AdminUpdateUserAttributesResponse())).Verifiable(); await _store.AddClaimsAsync(_userMock.Object, claims, CancellationToken.None).ConfigureAwait(false); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenAddClaimsWithEmptyListOfClaims_ThenAdminUpdateUserAttributesIsNeverCalled() { var claims = new List<Claim>(); await _store.AddClaimsAsync(_userMock.Object, claims, CancellationToken.None).ConfigureAwait(false); _cognitoClientMock.Verify(mock => mock.AdminUpdateUserAttributesAsync(It.IsAny<AdminUpdateUserAttributesRequest>(), It.IsAny<CancellationToken>()), Times.Never); } [Fact] public async void Test_GivenAUser_WhenRemoveClaimsWithAValidClaim_ThenAdminDeleteUserAttributesIsCalled() { var claims = new List<Claim>() { new Claim("Name1", "Value1") }; _cognitoClientMock.Setup(mock => mock.AdminGetUserAsync(It.IsAny<AdminGetUserRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(GET_USER_RESPONSE)).Verifiable(); _cognitoClientMock.Setup(mock => mock.AdminDeleteUserAttributesAsync(It.IsAny<AdminDeleteUserAttributesRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new AdminDeleteUserAttributesResponse())).Verifiable(); await _store.RemoveClaimsAsync(_userMock.Object, claims, CancellationToken.None).ConfigureAwait(false); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenRemoveClaimsWithAnInvalidClaim_ThenAdminDeleteUserAttributesIsNeverCalled() { var claims = new List<Claim>() { new Claim("Unknown", "Unknown") }; _cognitoClientMock.Setup(mock => mock.AdminGetUserAsync(It.IsAny<AdminGetUserRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(GET_USER_RESPONSE)).Verifiable(); _cognitoClientMock.Setup(mock => mock.AdminDeleteUserAttributesAsync(It.IsAny<AdminDeleteUserAttributesRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new AdminDeleteUserAttributesResponse())).Verifiable(); await _store.RemoveClaimsAsync(_userMock.Object, claims, CancellationToken.None).ConfigureAwait(false); _cognitoClientMock.Verify(mock => mock.AdminDeleteUserAttributesAsync(It.IsAny<AdminDeleteUserAttributesRequest>(), It.IsAny<CancellationToken>()), Times.Never); } [Fact] public async void Test_GivenAUser_WhenReplaceClaim_ThenThrowsANotSupportedException() { await Assert.ThrowsAsync<NotSupportedException>(() => _store.ReplaceClaimAsync(null, null, null, CancellationToken.None)).ConfigureAwait(false); } [Fact] public async void Test_GivenAClaim_WhenGetUsersForClaim_ThenThrowsANotSupportedException() { await Assert.ThrowsAsync<NotSupportedException>(() => _store.GetUsersForClaimAsync(new Claim("test", "test"), CancellationToken.None)).ConfigureAwait(false); } } }
122
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.AspNetCore.Identity.Cognito.Exceptions; using Amazon.CognitoIdentityProvider; using Amazon.CognitoIdentityProvider.Model; using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Identity; using Moq; using System; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Amazon.AspNetCore.Identity.Cognito.Tests { public partial class CognitoUserStoreTests { private Mock<IAmazonCognitoIdentityProvider> _cognitoClientMock; private Mock<CognitoUserPool> _cognitoPoolMock; private Mock<CognitoIdentityErrorDescriber> _errorsMock; private Mock<CognitoUser> _userMock; private CognitoUserStore<CognitoUser> _store; public CognitoUserStoreTests() { _cognitoClientMock = new Mock<IAmazonCognitoIdentityProvider>(); _cognitoPoolMock = new Mock<CognitoUserPool>("region_poolName", "clientID", _cognitoClientMock.Object, null) { CallBase = true }; _errorsMock = new Mock<CognitoIdentityErrorDescriber>(); _userMock = new Mock<CognitoUser>("userID", "clientID", _cognitoPoolMock.Object, _cognitoClientMock.Object, null, null, null, null); _store = new CognitoUserStore<CognitoUser>(_cognitoClientMock.Object, _cognitoPoolMock.Object, _errorsMock.Object); } [Theory] [InlineData("FORCE_CHANGE_PASSWORD", true)] [InlineData("CONFIRMED", false)] public async void Test_GivenAUserWithStatus_WhenIsPasswordChangeRequired_ThenResponseIsValid(string status, bool isPasswordChangeRequired) { var user = new CognitoUser("userID", "clientID", _cognitoPoolMock.Object, _cognitoClientMock.Object, null, status, null, null); var output = await _store.IsPasswordChangeRequiredAsync(user, CancellationToken.None).ConfigureAwait(false); Assert.Equal(isPasswordChangeRequired, output); } [Theory] [InlineData("RESET_REQUIRED", true)] [InlineData("CONFIRMED", false)] public async void Test_GivenAUserWithStatus_WhenIsPasswordResetRequired_ThenResponseIsValid(string status, bool isPasswordResetRequired) { var user = new CognitoUser("userID", "clientID", _cognitoPoolMock.Object, _cognitoClientMock.Object, null, status, null, null); var output = await _store.IsPasswordResetRequiredAsync(user, CancellationToken.None).ConfigureAwait(false); Assert.Equal(isPasswordResetRequired, output); } [Fact] public async void Test_GivenAUser_WhenResetPassword_ThenTheRequestIsSuccessful() { _cognitoClientMock.Setup(mock => mock.AdminResetUserPasswordAsync(It.IsAny<AdminResetUserPasswordRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new AdminResetUserPasswordResponse())).Verifiable(); var output = await _store.ResetPasswordAsync(_userMock.Object, CancellationToken.None).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenCreate_ThenTheUserGetsAddedToThePool() { var output = await _store.CreateAsync(_userMock.Object, "password", null, CancellationToken.None).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); } [Fact] public async void Test_GivenAUser_WhenAdminConfirmSignUp_ThenTheRequestIsSuccessful() { _cognitoClientMock.Setup(mock => mock.AdminConfirmSignUpAsync(It.IsAny<AdminConfirmSignUpRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new AdminConfirmSignUpResponse())).Verifiable(); var output = await _store.AdminConfirmSignUpAsync(_userMock.Object, CancellationToken.None).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenGetUserAttributeVerificationCodeOtherThanEmailOrPhone_ThenThrowsArgumentException() { await Assert.ThrowsAsync<ArgumentException>(() => _store.GetUserAttributeVerificationCodeAsync(_userMock.Object, "UNKNOWN_ATTRIBUTE", CancellationToken.None)).ConfigureAwait(false); } [Fact] public async void Test_GivenAUser_WhenGetUserAttributeVerificationCode_ThenTheRequestIsSuccessfun() { _cognitoClientMock.Setup(mock => mock.GetUserAttributeVerificationCodeAsync(It.IsAny<GetUserAttributeVerificationCodeRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new GetUserAttributeVerificationCodeResponse())).Verifiable(); _userMock.Object.SessionTokens = new CognitoUserSession(null, null, null, DateTime.Now, DateTime.MaxValue); var output = await _store.GetUserAttributeVerificationCodeAsync(_userMock.Object, CognitoAttribute.PhoneNumber.AttributeName, CancellationToken.None).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenVerifyUserAttribute_ThenTheRequestIsSuccessfun() { _cognitoClientMock.Setup(mock => mock.VerifyUserAttributeAsync(It.IsAny<VerifyUserAttributeRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new VerifyUserAttributeResponse())).Verifiable(); _userMock.Object.SessionTokens = new CognitoUserSession(null, null, null, DateTime.Now, DateTime.MaxValue); var output = await _store.VerifyUserAttributeAsync(_userMock.Object, CognitoAttribute.PhoneNumber.AttributeName, "code", CancellationToken.None).ConfigureAwait(false); Assert.Equal(IdentityResult.Success, output); _cognitoClientMock.Verify(); } } }
118
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.CognitoIdentityProvider.Model; using Moq; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Amazon.AspNetCore.Identity.Cognito.Tests { public partial class CognitoUserStoreTests { [Fact] public async void Test_GivenAnEmail_WhenFindByEmail_ThenTheUserIsRetrieved() { var username = "UserName"; var status = "CONFIRMED"; var response = new ListUsersResponse() { Users = new List<UserType>() { new UserType() { Username = username, UserStatus = status, Attributes = new List<AttributeType>() } } }; _cognitoClientMock.Setup(mock => mock.ListUsersAsync(It.IsAny<ListUsersRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(response)).Verifiable(); var user = await _store.FindByEmailAsync("[email protected]", CancellationToken.None).ConfigureAwait(false); Assert.Equal(username, user.Username); Assert.Equal(status, user.Status); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenGetNormalizedEmail_ThenThrowsANotSupportedException() { await Assert.ThrowsAsync<NotSupportedException>(() => _store.GetNormalizedEmailAsync(_userMock.Object, CancellationToken.None)).ConfigureAwait(false); } [Fact] public async void Test_GivenAUser_WhenSetEmailConfirmed_ThenThrowsANotSupportedException() { await Assert.ThrowsAsync<NotSupportedException>(() => _store.SetEmailConfirmedAsync(_userMock.Object, true, CancellationToken.None)).ConfigureAwait(false); } [Fact] public async void Test_GivenAUser_WhenSetNormalizedEmail_ThenThrowsANotSupportedException() { await Assert.ThrowsAsync<NotSupportedException>(() => _store.SetNormalizedEmailAsync(_userMock.Object, "email", CancellationToken.None)).ConfigureAwait(false); } } }
71
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Threading; using Xunit; namespace Amazon.AspNetCore.Identity.Cognito.Tests { public partial class CognitoUserStoreTests { [Fact] public async void Test_GivenAUser_WhenSetPhoneNumberConfirmed_ThenThrowsANotSupportedException() { await Assert.ThrowsAsync<NotSupportedException>(() => _store.SetPhoneNumberConfirmedAsync(_userMock.Object, true, CancellationToken.None)).ConfigureAwait(false); } } }
32
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.CognitoIdentityProvider.Model; using Moq; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Amazon.AspNetCore.Identity.Cognito.Tests { public partial class CognitoUserStoreTests { AdminListGroupsForUserResponse LIST_GROUPS_FOR_USERS_RESPONSE = new AdminListGroupsForUserResponse() { Groups = new List<GroupType>() { new GroupType() { GroupName = "group1"}, new GroupType() { GroupName = "group2"}, new GroupType() { GroupName = "group3"}, } }; [Fact] public async void Test_GivenAUser_WhenGetUserId_ThenTheUserIdIsRetrieved() { var userId = await _store.GetUserIdAsync(_userMock.Object, CancellationToken.None).ConfigureAwait(false); Assert.Equal(_userMock.Object.UserID, userId); } [Fact] public async void Test_GivenAUser_WhenGetUserName_ThenTheUserNameIsRetrieved() { var userName = await _store.GetUserNameAsync(_userMock.Object, CancellationToken.None).ConfigureAwait(false); Assert.Equal(_userMock.Object.Username, userName); } [Fact] public async void Test_GivenAUser_WhenDelete_ThenAdminDeleteUserAsyncIsCalled() { _cognitoClientMock.Setup(mock => mock.AdminDeleteUserAsync(It.IsAny<AdminDeleteUserRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new AdminDeleteUserResponse())).Verifiable(); await _store.DeleteAsync(_userMock.Object, CancellationToken.None).ConfigureAwait(false); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenAddToRole_ThenAdminAddUserToGroupAsyncIsCalled() { _cognitoClientMock.Setup(mock => mock.AdminAddUserToGroupAsync(It.IsAny<AdminAddUserToGroupRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new AdminAddUserToGroupResponse())).Verifiable(); await _store.AddToRoleAsync(_userMock.Object, "roleName", CancellationToken.None).ConfigureAwait(false); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenRemoveFromRole_ThenAdminRemoveUserFromGroupAsyncIsCalled() { _cognitoClientMock.Setup(mock => mock.AdminRemoveUserFromGroupAsync(It.IsAny<AdminRemoveUserFromGroupRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new AdminRemoveUserFromGroupResponse())).Verifiable(); await _store.RemoveFromRoleAsync(_userMock.Object, "roleName", CancellationToken.None).ConfigureAwait(false); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenGetRoles_ThenTheUserRolesAreRetrieved() { _cognitoClientMock.Setup(mock => mock.AdminListGroupsForUserAsync(It.IsAny<AdminListGroupsForUserRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(LIST_GROUPS_FOR_USERS_RESPONSE)).Verifiable(); var output = await _store.GetRolesAsync(_userMock.Object, CancellationToken.None).ConfigureAwait(false); Assert.Equal(LIST_GROUPS_FOR_USERS_RESPONSE.Groups.Count, output.Count); Assert.Equal(LIST_GROUPS_FOR_USERS_RESPONSE.Groups[0].GroupName, output[0]); Assert.Equal(LIST_GROUPS_FOR_USERS_RESPONSE.Groups[1].GroupName, output[1]); Assert.Equal(LIST_GROUPS_FOR_USERS_RESPONSE.Groups[2].GroupName, output[2]); _cognitoClientMock.Verify(); } [Theory] [InlineData("group1", true)] [InlineData("unknownGroup", false)] public async void Test_GivenAUserAndARoleName_WhenIsInRole_ThenTheResponseIsValid(string roleName, bool isInRole) { _cognitoClientMock.Setup(mock => mock.AdminListGroupsForUserAsync(It.IsAny<AdminListGroupsForUserRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(LIST_GROUPS_FOR_USERS_RESPONSE)).Verifiable(); var output = await _store.IsInRoleAsync(_userMock.Object, roleName, CancellationToken.None).ConfigureAwait(false); Assert.Equal(isInRole, output); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenGetNormalizedUserName_ThenThrowsANotSupportedException() { await Assert.ThrowsAsync<NotSupportedException>(() => _store.GetNormalizedUserNameAsync(_userMock.Object, CancellationToken.None)).ConfigureAwait(false); } [Fact] public async void Test_GivenAUser_WhenSetNormalizedUserName_ThenThrowsANotSupportedException() { await Assert.ThrowsAsync<NotSupportedException>(() => _store.SetNormalizedUserNameAsync(_userMock.Object, "userName", CancellationToken.None)).ConfigureAwait(false); } [Fact] public async void Test_GivenAUser_WhenSetSetUserName_ThenThrowsANotSupportedException() { await Assert.ThrowsAsync<NotSupportedException>(() => _store.SetUserNameAsync(_userMock.Object, "userName", CancellationToken.None)).ConfigureAwait(false); } } }
118
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.CognitoIdentityProvider.Model; using Moq; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Amazon.AspNetCore.Identity.Cognito.Tests { public partial class CognitoUserStoreTests { [Fact] public async void Test_GivenAUser_WhenGetTwoFactorEnabledWithAnMFAOption_ThenTheResponseIsTrue() { var response = new AdminGetUserResponse() { MFAOptions = new List<MFAOptionType>() { new MFAOptionType() } }; _cognitoClientMock.Setup(mock => mock.AdminGetUserAsync(It.IsAny<AdminGetUserRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(response)).Verifiable(); var output = await _store.GetTwoFactorEnabledAsync(_userMock.Object, CancellationToken.None).ConfigureAwait(false); Assert.True(output); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenGetTwoFactorEnabledWithoutAnMFAOption_ThenTheResponseIsFalse() { var response = new AdminGetUserResponse() { MFAOptions = new List<MFAOptionType>() }; _cognitoClientMock.Setup(mock => mock.AdminGetUserAsync(It.IsAny<AdminGetUserRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(response)).Verifiable(); var output = await _store.GetTwoFactorEnabledAsync(_userMock.Object, CancellationToken.None).ConfigureAwait(false); Assert.False(output); _cognitoClientMock.Verify(); } [Fact] public async void Test_GivenAUser_WhenSetTwoFactorEnabled_ThenAdminSetUserSettingsAsyncIsCalled() { _cognitoClientMock.Setup(mock => mock.AdminSetUserSettingsAsync(It.IsAny<AdminSetUserSettingsRequest>(), It.IsAny<CancellationToken>())).Returns(Task.FromResult(new AdminSetUserSettingsResponse())).Verifiable(); await _store.SetTwoFactorEnabledAsync(_userMock.Object, false, CancellationToken.None).ConfigureAwait(false); _cognitoClientMock.Verify(); } } }
65
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.AspNetCore.Identity.Cognito.Exceptions; using Amazon.CognitoIdentityProvider; using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Moq; using System; namespace Amazon.AspNetCore.Identity.Cognito.Tests { public class ManagerTestBase { protected Mock<IHttpContextAccessor> contextAccessorMock; protected Mock<CognitoUserClaimsPrincipalFactory<CognitoUser>> claimsFactoryMock; protected Mock<IOptions<IdentityOptions>> optionsAccessorMock; protected Mock<IUserConfirmation<CognitoUser>> userConfirmationMock; protected Mock<ILogger<SignInManager<CognitoUser>>> loggerSigninManagerMock; protected Mock<IAuthenticationSchemeProvider> schemesMock; protected Mock<IAmazonCognitoIdentityProvider> cognitoClientMock; protected Mock<CognitoUserPool> cognitoPoolMock; protected Mock<CognitoIdentityErrorDescriber> errorsMock; protected Mock<CognitoUserStore<CognitoUser>> userStoreMock; protected Mock<IPasswordHasher<CognitoUser>> passwordHasherMock; protected Mock<IUserValidator<CognitoUser>> userValidatorsMock; protected Mock<IPasswordValidator<CognitoUser>> passwordValidatorsMock; protected CognitoKeyNormalizer keyNormalizer; protected Mock<IServiceProvider> servicesMock; protected Mock<ILogger<UserManager<CognitoUser>>> loggerUserManagerMock; public ManagerTestBase() { cognitoClientMock = new Mock<IAmazonCognitoIdentityProvider>(); cognitoPoolMock = new Mock<CognitoUserPool>("region_poolName", "clientID", cognitoClientMock.Object, null); errorsMock = new Mock<CognitoIdentityErrorDescriber>(); optionsAccessorMock = new Mock<IOptions<IdentityOptions>>(); var idOptions = new IdentityOptions(); idOptions.Lockout.AllowedForNewUsers = false; optionsAccessorMock.Setup(o => o.Value).Returns(idOptions); contextAccessorMock = new Mock<IHttpContextAccessor>(); userConfirmationMock = new Mock<IUserConfirmation<CognitoUser>>(); loggerSigninManagerMock = new Mock<ILogger<SignInManager<CognitoUser>>>(); schemesMock = new Mock<IAuthenticationSchemeProvider>(); userStoreMock = new Mock<CognitoUserStore<CognitoUser>>(cognitoClientMock.Object, cognitoPoolMock.Object, errorsMock.Object); passwordHasherMock = new Mock<IPasswordHasher<CognitoUser>>(); userValidatorsMock = new Mock<IUserValidator<CognitoUser>>(); passwordValidatorsMock = new Mock<IPasswordValidator<CognitoUser>>(); keyNormalizer = new CognitoKeyNormalizer(); servicesMock = new Mock<IServiceProvider>(); loggerUserManagerMock = new Mock<ILogger<UserManager<CognitoUser>>>(); } public CognitoUser GetCognitoUser() { return new CognitoUser("userId", "clientId", cognitoPoolMock.Object, cognitoClientMock.Object); } } }
76
aws-aspnet-cognito-identity-provider
aws
C#
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using Amazon.Extensions.CognitoAuthentication; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Moq; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; namespace Amazon.AspNetCore.Identity.Cognito.Tests { public static class MockUtils { public const string loginProvider = "login"; public const string providerKey = "fookey"; /// <summary> /// This creates an http context. /// </summary> /// <param name="cognitoUser">The Cognito User to link to the context</param> /// <param name="scheme">The scheme to signin the user into</param> /// <returns></returns> public static DefaultHttpContext MockContext(CognitoUser cognitoUser, string scheme) { var context = new DefaultHttpContext(); var authMock = new Mock<IAuthenticationService>(); var userPrincipal = new ClaimsPrincipal(); userPrincipal.AddIdentity(new ClaimsIdentity(new List<Claim>() { new Claim(ClaimTypes.Name, cognitoUser.UserID), new Claim(providerKey, loginProvider), new Claim(ClaimTypes.AuthenticationMethod, providerKey) })); var authenticationTicket = new AuthenticationTicket(userPrincipal, scheme); var authenticateResult = AuthenticateResult.Success(authenticationTicket); context.RequestServices = new ServiceCollection().AddSingleton(authMock.Object).BuildServiceProvider(); authMock.Setup(a => a.AuthenticateAsync(context, scheme)).Returns(Task.FromResult(authenticateResult)).Verifiable(); return context; } } }
60
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 using software.amazon.cryptography.primitives.internaldafny.types; namespace software.amazon.cryptography.internaldafny { public partial class SynchronizedLocalCMC : software.amazon.cryptography.materialproviders.internaldafny.types.ICryptographicMaterialsCache { public LocalCMC_Compile.LocalCMC wrapped; public SynchronizedLocalCMC(LocalCMC_Compile.LocalCMC cmc) { this.wrapped = cmc; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] public Wrappers_Compile._IResult<_System._ITuple0, software.amazon.cryptography.materialproviders.internaldafny.types._IError> PutCacheEntry(software.amazon.cryptography.materialproviders.internaldafny.types._IPutCacheEntryInput input) { return this.wrapped.PutCacheEntry(input); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] public Wrappers_Compile._IResult<_System._ITuple0, software.amazon.cryptography.materialproviders.internaldafny.types._IError> UpdateUsageMetadata(software.amazon.cryptography.materialproviders.internaldafny.types._IUpdateUsageMetadataInput input) { return this.wrapped.UpdateUsageMetadata(input); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] public Wrappers_Compile._IResult<software.amazon.cryptography.materialproviders.internaldafny.types._IGetCacheEntryOutput, software.amazon.cryptography.materialproviders.internaldafny.types._IError> GetCacheEntry(software.amazon.cryptography.materialproviders.internaldafny.types._IGetCacheEntryInput input) { return this.wrapped.GetCacheEntry(input); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] public Wrappers_Compile._IResult<_System._ITuple0, software.amazon.cryptography.materialproviders.internaldafny.types._IError> DeleteCacheEntry(software.amazon.cryptography.materialproviders.internaldafny.types._IDeleteCacheEntryInput input) { return this.wrapped.DeleteCacheEntry(input); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] public Wrappers_Compile._IResult<software.amazon.cryptography.materialproviders.internaldafny.types._IGetCacheEntryOutput, software.amazon.cryptography.materialproviders.internaldafny.types._IError> GetCacheEntry_k(software.amazon.cryptography.materialproviders.internaldafny.types._IGetCacheEntryInput input) { return this.wrapped.GetCacheEntry_k(input); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] public Wrappers_Compile._IResult<_System._ITuple0, software.amazon.cryptography.materialproviders.internaldafny.types._IError> PutCacheEntry_k(software.amazon.cryptography.materialproviders.internaldafny.types._IPutCacheEntryInput input) { return this.wrapped.PutCacheEntry_k(input); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] public Wrappers_Compile._IResult<_System._ITuple0, software.amazon.cryptography.materialproviders.internaldafny.types._IError> DeleteCacheEntry_k(software.amazon.cryptography.materialproviders.internaldafny.types._IDeleteCacheEntryInput input) { return this.wrapped.DeleteCacheEntry_k(input); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] public Wrappers_Compile._IResult<_System._ITuple0, software.amazon.cryptography.materialproviders.internaldafny.types._IError> UpdateUsageMetadata_k(software.amazon.cryptography.materialproviders.internaldafny.types._IUpdateUsageMetadataInput input) { return this.wrapped.UpdateUsageMetadata_k(input); } } }
57
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { using Amazon.Runtime; public class AesWrappingAlg : ConstantClass { public static readonly AesWrappingAlg ALG_AES128_GCM_IV12_TAG16 = new AesWrappingAlg ("ALG_AES128_GCM_IV12_TAG16"); public static readonly AesWrappingAlg ALG_AES192_GCM_IV12_TAG16 = new AesWrappingAlg ("ALG_AES192_GCM_IV12_TAG16"); public static readonly AesWrappingAlg ALG_AES256_GCM_IV12_TAG16 = new AesWrappingAlg ("ALG_AES256_GCM_IV12_TAG16"); public static readonly AesWrappingAlg [] Values = { ALG_AES128_GCM_IV12_TAG16 , ALG_AES192_GCM_IV12_TAG16 , ALG_AES256_GCM_IV12_TAG16 } ; public AesWrappingAlg (string value) : base(value) {} } }
20
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class AlgorithmSuiteId { private AWS.Cryptography.MaterialProviders.ESDKAlgorithmSuiteId _eSDK ; private AWS.Cryptography.MaterialProviders.DBEAlgorithmSuiteId _dBE ; public AWS.Cryptography.MaterialProviders.ESDKAlgorithmSuiteId ESDK { get { return this._eSDK; } set { this._eSDK = value; } } public bool IsSetESDK () { return this._eSDK != null; } public AWS.Cryptography.MaterialProviders.DBEAlgorithmSuiteId DBE { get { return this._dBE; } set { this._dBE = value; } } public bool IsSetDBE () { return this._dBE != null; } public void Validate() { var numberOfPropertiesSet = Convert.ToUInt16(IsSetESDK()) + Convert.ToUInt16(IsSetDBE()) ; if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); } } }
33
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class AlgorithmSuiteInfo { private AWS.Cryptography.MaterialProviders.AlgorithmSuiteId _id ; private System.IO.MemoryStream _binaryId ; private int? _messageVersion ; private AWS.Cryptography.MaterialProviders.Encrypt _encrypt ; private AWS.Cryptography.MaterialProviders.DerivationAlgorithm _kdf ; private AWS.Cryptography.MaterialProviders.DerivationAlgorithm _commitment ; private AWS.Cryptography.MaterialProviders.SignatureAlgorithm _signature ; private AWS.Cryptography.MaterialProviders.SymmetricSignatureAlgorithm _symmetricSignature ; private AWS.Cryptography.MaterialProviders.EdkWrappingAlgorithm _edkWrapping ; public AWS.Cryptography.MaterialProviders.AlgorithmSuiteId Id { get { return this._id; } set { this._id = value; } } public bool IsSetId () { return this._id != null; } public System.IO.MemoryStream BinaryId { get { return this._binaryId; } set { this._binaryId = value; } } public bool IsSetBinaryId () { return this._binaryId != null; } public int MessageVersion { get { return this._messageVersion.GetValueOrDefault(); } set { this._messageVersion = value; } } public bool IsSetMessageVersion () { return this._messageVersion.HasValue; } public AWS.Cryptography.MaterialProviders.Encrypt Encrypt { get { return this._encrypt; } set { this._encrypt = value; } } public bool IsSetEncrypt () { return this._encrypt != null; } public AWS.Cryptography.MaterialProviders.DerivationAlgorithm Kdf { get { return this._kdf; } set { this._kdf = value; } } public bool IsSetKdf () { return this._kdf != null; } public AWS.Cryptography.MaterialProviders.DerivationAlgorithm Commitment { get { return this._commitment; } set { this._commitment = value; } } public bool IsSetCommitment () { return this._commitment != null; } public AWS.Cryptography.MaterialProviders.SignatureAlgorithm Signature { get { return this._signature; } set { this._signature = value; } } public bool IsSetSignature () { return this._signature != null; } public AWS.Cryptography.MaterialProviders.SymmetricSignatureAlgorithm SymmetricSignature { get { return this._symmetricSignature; } set { this._symmetricSignature = value; } } public bool IsSetSymmetricSignature () { return this._symmetricSignature != null; } public AWS.Cryptography.MaterialProviders.EdkWrappingAlgorithm EdkWrapping { get { return this._edkWrapping; } set { this._edkWrapping = value; } } public bool IsSetEdkWrapping () { return this._edkWrapping != null; } public void Validate() { if (!IsSetId()) throw new System.ArgumentException("Missing value for required property 'Id'"); if (!IsSetBinaryId()) throw new System.ArgumentException("Missing value for required property 'BinaryId'"); if (!IsSetMessageVersion()) throw new System.ArgumentException("Missing value for required property 'MessageVersion'"); if (!IsSetEncrypt()) throw new System.ArgumentException("Missing value for required property 'Encrypt'"); if (!IsSetKdf()) throw new System.ArgumentException("Missing value for required property 'Kdf'"); if (!IsSetCommitment()) throw new System.ArgumentException("Missing value for required property 'Commitment'"); if (!IsSetSignature()) throw new System.ArgumentException("Missing value for required property 'Signature'"); if (!IsSetSymmetricSignature()) throw new System.ArgumentException("Missing value for required property 'SymmetricSignature'"); if (!IsSetEdkWrapping()) throw new System.ArgumentException("Missing value for required property 'EdkWrapping'"); } } }
93
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class AwsCryptographicMaterialProvidersException : Exception { public AwsCryptographicMaterialProvidersException(string message) : base(message) {} } }
10
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class BeaconKeyMaterials { private string _beaconKeyIdentifier ; private System.IO.MemoryStream _beaconKey ; private System.Collections.Generic.Dictionary<string, System.IO.MemoryStream> _hmacKeys ; public string BeaconKeyIdentifier { get { return this._beaconKeyIdentifier; } set { this._beaconKeyIdentifier = value; } } public bool IsSetBeaconKeyIdentifier () { return this._beaconKeyIdentifier != null; } public System.IO.MemoryStream BeaconKey { get { return this._beaconKey; } set { this._beaconKey = value; } } public bool IsSetBeaconKey () { return this._beaconKey != null; } public System.Collections.Generic.Dictionary<string, System.IO.MemoryStream> HmacKeys { get { return this._hmacKeys; } set { this._hmacKeys = value; } } public bool IsSetHmacKeys () { return this._hmacKeys != null; } public void Validate() { if (!IsSetBeaconKeyIdentifier()) throw new System.ArgumentException("Missing value for required property 'BeaconKeyIdentifier'"); } } }
37
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using System.IO; using System.Collections.Generic; using AWS.Cryptography.MaterialProviders; using software.amazon.cryptography.materialproviders.internaldafny.types; namespace AWS.Cryptography.MaterialProviders { internal class BranchKeyIdSupplier : BranchKeyIdSupplierBase { internal readonly software.amazon.cryptography.materialproviders.internaldafny.types.IBranchKeyIdSupplier _impl; internal BranchKeyIdSupplier(software.amazon.cryptography.materialproviders.internaldafny.types.IBranchKeyIdSupplier impl) { this._impl = impl; } protected override AWS.Cryptography.MaterialProviders.GetBranchKeyIdOutput _GetBranchKeyId(AWS.Cryptography.MaterialProviders.GetBranchKeyIdInput input) { software.amazon.cryptography.materialproviders.internaldafny.types._IGetBranchKeyIdInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N17_materialProviders__S19_GetBranchKeyIdInput(input); Wrappers_Compile._IResult<software.amazon.cryptography.materialproviders.internaldafny.types._IGetBranchKeyIdOutput, software.amazon.cryptography.materialproviders.internaldafny.types._IError> result = this._impl.GetBranchKeyId(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); return TypeConversion.FromDafny_N3_aws__N12_cryptography__N17_materialProviders__S20_GetBranchKeyIdOutput(result.dtor_value); } } }
20
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public abstract class BranchKeyIdSupplierBase : IBranchKeyIdSupplier { public AWS.Cryptography.MaterialProviders.GetBranchKeyIdOutput GetBranchKeyId ( AWS.Cryptography.MaterialProviders.GetBranchKeyIdInput input ) { input.Validate(); return _GetBranchKeyId ( input ) ; } protected abstract AWS.Cryptography.MaterialProviders.GetBranchKeyIdOutput _GetBranchKeyId ( AWS.Cryptography.MaterialProviders.GetBranchKeyIdInput input ) ; } }
14
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class BranchKeyMaterials { private string _branchKeyVersion ; private System.IO.MemoryStream _branchKey ; public string BranchKeyVersion { get { return this._branchKeyVersion; } set { this._branchKeyVersion = value; } } public bool IsSetBranchKeyVersion () { return this._branchKeyVersion != null; } public System.IO.MemoryStream BranchKey { get { return this._branchKey; } set { this._branchKey = value; } } public bool IsSetBranchKey () { return this._branchKey != null; } public void Validate() { if (!IsSetBranchKeyVersion()) throw new System.ArgumentException("Missing value for required property 'BranchKeyVersion'"); if (!IsSetBranchKey()) throw new System.ArgumentException("Missing value for required property 'BranchKey'"); } } }
30
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using System.IO; using System.Collections.Generic; using AWS.Cryptography.MaterialProviders; using software.amazon.cryptography.materialproviders.internaldafny.types; namespace AWS.Cryptography.MaterialProviders { internal class ClientSupplier : ClientSupplierBase { internal readonly software.amazon.cryptography.materialproviders.internaldafny.types.IClientSupplier _impl; internal ClientSupplier(software.amazon.cryptography.materialproviders.internaldafny.types.IClientSupplier impl) { this._impl = impl; } protected override Amazon.KeyManagementService.IAmazonKeyManagementService _GetClient(AWS.Cryptography.MaterialProviders.GetClientInput input) { software.amazon.cryptography.materialproviders.internaldafny.types._IGetClientInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N17_materialProviders__S14_GetClientInput(input); Wrappers_Compile._IResult<software.amazon.cryptography.services.kms.internaldafny.types.IKMSClient, software.amazon.cryptography.materialproviders.internaldafny.types._IError> result = this._impl.GetClient(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); return TypeConversion.FromDafny_N3_aws__N12_cryptography__N17_materialProviders__S15_GetClientOutput(result.dtor_value); } } }
20
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public abstract class ClientSupplierBase : IClientSupplier { public Amazon.KeyManagementService.IAmazonKeyManagementService GetClient ( AWS.Cryptography.MaterialProviders.GetClientInput input ) { input.Validate(); return _GetClient ( input ) ; } protected abstract Amazon.KeyManagementService.IAmazonKeyManagementService _GetClient ( AWS.Cryptography.MaterialProviders.GetClientInput input ) ; } }
14
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CollectionOfErrors : Exception { public readonly System.Collections.Generic.List<Exception> list; public CollectionOfErrors(System.Collections.Generic.List<Exception> list, string message) : base(message) { this.list = list; } public CollectionOfErrors(string message) : base(message) { this.list = new System.Collections.Generic.List<Exception>(); } public CollectionOfErrors() : base("CollectionOfErrors") { this.list = new System.Collections.Generic.List<Exception>(); } } }
14
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CommitmentPolicy { private AWS.Cryptography.MaterialProviders.ESDKCommitmentPolicy _eSDK ; private AWS.Cryptography.MaterialProviders.DBECommitmentPolicy _dBE ; public AWS.Cryptography.MaterialProviders.ESDKCommitmentPolicy ESDK { get { return this._eSDK; } set { this._eSDK = value; } } public bool IsSetESDK () { return this._eSDK != null; } public AWS.Cryptography.MaterialProviders.DBECommitmentPolicy DBE { get { return this._dBE; } set { this._dBE = value; } } public bool IsSetDBE () { return this._dBE != null; } public void Validate() { var numberOfPropertiesSet = Convert.ToUInt16(IsSetESDK()) + Convert.ToUInt16(IsSetDBE()) ; if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); } } }
33
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateAwsKmsDiscoveryKeyringInput { private Amazon.KeyManagementService.IAmazonKeyManagementService _kmsClient ; private AWS.Cryptography.MaterialProviders.DiscoveryFilter _discoveryFilter ; private System.Collections.Generic.List<string> _grantTokens ; public Amazon.KeyManagementService.IAmazonKeyManagementService KmsClient { get { return this._kmsClient; } set { this._kmsClient = value; } } public bool IsSetKmsClient () { return this._kmsClient != null; } public AWS.Cryptography.MaterialProviders.DiscoveryFilter DiscoveryFilter { get { return this._discoveryFilter; } set { this._discoveryFilter = value; } } public bool IsSetDiscoveryFilter () { return this._discoveryFilter != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } public bool IsSetGrantTokens () { return this._grantTokens != null; } public void Validate() { if (!IsSetKmsClient()) throw new System.ArgumentException("Missing value for required property 'KmsClient'"); } } }
37
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateAwsKmsDiscoveryMultiKeyringInput { private System.Collections.Generic.List<string> _regions ; private AWS.Cryptography.MaterialProviders.DiscoveryFilter _discoveryFilter ; private AWS.Cryptography.MaterialProviders.IClientSupplier _clientSupplier ; private System.Collections.Generic.List<string> _grantTokens ; public System.Collections.Generic.List<string> Regions { get { return this._regions; } set { this._regions = value; } } public bool IsSetRegions () { return this._regions != null; } public AWS.Cryptography.MaterialProviders.DiscoveryFilter DiscoveryFilter { get { return this._discoveryFilter; } set { this._discoveryFilter = value; } } public bool IsSetDiscoveryFilter () { return this._discoveryFilter != null; } public AWS.Cryptography.MaterialProviders.IClientSupplier ClientSupplier { get { return this._clientSupplier; } set { this._clientSupplier = value; } } public bool IsSetClientSupplier () { return this._clientSupplier != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } public bool IsSetGrantTokens () { return this._grantTokens != null; } public void Validate() { if (!IsSetRegions()) throw new System.ArgumentException("Missing value for required property 'Regions'"); } } }
45
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateAwsKmsHierarchicalKeyringInput { private string _branchKeyId ; private AWS.Cryptography.MaterialProviders.IBranchKeyIdSupplier _branchKeyIdSupplier ; private AWS.Cryptography.KeyStore.KeyStore _keyStore ; private long? _ttlSeconds ; private int? _maxCacheSize ; public string BranchKeyId { get { return this._branchKeyId; } set { this._branchKeyId = value; } } public bool IsSetBranchKeyId () { return this._branchKeyId != null; } public AWS.Cryptography.MaterialProviders.IBranchKeyIdSupplier BranchKeyIdSupplier { get { return this._branchKeyIdSupplier; } set { this._branchKeyIdSupplier = value; } } public bool IsSetBranchKeyIdSupplier () { return this._branchKeyIdSupplier != null; } public AWS.Cryptography.KeyStore.KeyStore KeyStore { get { return this._keyStore; } set { this._keyStore = value; } } public bool IsSetKeyStore () { return this._keyStore != null; } public long TtlSeconds { get { return this._ttlSeconds.GetValueOrDefault(); } set { this._ttlSeconds = value; } } public bool IsSetTtlSeconds () { return this._ttlSeconds.HasValue; } public int MaxCacheSize { get { return this._maxCacheSize.GetValueOrDefault(); } set { this._maxCacheSize = value; } } public bool IsSetMaxCacheSize () { return this._maxCacheSize.HasValue; } public void Validate() { if (!IsSetKeyStore()) throw new System.ArgumentException("Missing value for required property 'KeyStore'"); if (!IsSetTtlSeconds()) throw new System.ArgumentException("Missing value for required property 'TtlSeconds'"); } } }
54
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateAwsKmsKeyringInput { private string _kmsKeyId ; private Amazon.KeyManagementService.IAmazonKeyManagementService _kmsClient ; private System.Collections.Generic.List<string> _grantTokens ; public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } public bool IsSetKmsKeyId () { return this._kmsKeyId != null; } public Amazon.KeyManagementService.IAmazonKeyManagementService KmsClient { get { return this._kmsClient; } set { this._kmsClient = value; } } public bool IsSetKmsClient () { return this._kmsClient != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } public bool IsSetGrantTokens () { return this._grantTokens != null; } public void Validate() { if (!IsSetKmsKeyId()) throw new System.ArgumentException("Missing value for required property 'KmsKeyId'"); if (!IsSetKmsClient()) throw new System.ArgumentException("Missing value for required property 'KmsClient'"); } } }
38
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateAwsKmsMrkDiscoveryKeyringInput { private Amazon.KeyManagementService.IAmazonKeyManagementService _kmsClient ; private AWS.Cryptography.MaterialProviders.DiscoveryFilter _discoveryFilter ; private System.Collections.Generic.List<string> _grantTokens ; private string _region ; public Amazon.KeyManagementService.IAmazonKeyManagementService KmsClient { get { return this._kmsClient; } set { this._kmsClient = value; } } public bool IsSetKmsClient () { return this._kmsClient != null; } public AWS.Cryptography.MaterialProviders.DiscoveryFilter DiscoveryFilter { get { return this._discoveryFilter; } set { this._discoveryFilter = value; } } public bool IsSetDiscoveryFilter () { return this._discoveryFilter != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } public bool IsSetGrantTokens () { return this._grantTokens != null; } public string Region { get { return this._region; } set { this._region = value; } } public bool IsSetRegion () { return this._region != null; } public void Validate() { if (!IsSetKmsClient()) throw new System.ArgumentException("Missing value for required property 'KmsClient'"); if (!IsSetRegion()) throw new System.ArgumentException("Missing value for required property 'Region'"); } } }
46
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateAwsKmsMrkDiscoveryMultiKeyringInput { private System.Collections.Generic.List<string> _regions ; private AWS.Cryptography.MaterialProviders.DiscoveryFilter _discoveryFilter ; private AWS.Cryptography.MaterialProviders.IClientSupplier _clientSupplier ; private System.Collections.Generic.List<string> _grantTokens ; public System.Collections.Generic.List<string> Regions { get { return this._regions; } set { this._regions = value; } } public bool IsSetRegions () { return this._regions != null; } public AWS.Cryptography.MaterialProviders.DiscoveryFilter DiscoveryFilter { get { return this._discoveryFilter; } set { this._discoveryFilter = value; } } public bool IsSetDiscoveryFilter () { return this._discoveryFilter != null; } public AWS.Cryptography.MaterialProviders.IClientSupplier ClientSupplier { get { return this._clientSupplier; } set { this._clientSupplier = value; } } public bool IsSetClientSupplier () { return this._clientSupplier != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } public bool IsSetGrantTokens () { return this._grantTokens != null; } public void Validate() { if (!IsSetRegions()) throw new System.ArgumentException("Missing value for required property 'Regions'"); } } }
45
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateAwsKmsMrkKeyringInput { private string _kmsKeyId ; private Amazon.KeyManagementService.IAmazonKeyManagementService _kmsClient ; private System.Collections.Generic.List<string> _grantTokens ; public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } public bool IsSetKmsKeyId () { return this._kmsKeyId != null; } public Amazon.KeyManagementService.IAmazonKeyManagementService KmsClient { get { return this._kmsClient; } set { this._kmsClient = value; } } public bool IsSetKmsClient () { return this._kmsClient != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } public bool IsSetGrantTokens () { return this._grantTokens != null; } public void Validate() { if (!IsSetKmsKeyId()) throw new System.ArgumentException("Missing value for required property 'KmsKeyId'"); if (!IsSetKmsClient()) throw new System.ArgumentException("Missing value for required property 'KmsClient'"); } } }
38
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateAwsKmsMrkMultiKeyringInput { private string _generator ; private System.Collections.Generic.List<string> _kmsKeyIds ; private AWS.Cryptography.MaterialProviders.IClientSupplier _clientSupplier ; private System.Collections.Generic.List<string> _grantTokens ; public string Generator { get { return this._generator; } set { this._generator = value; } } public bool IsSetGenerator () { return this._generator != null; } public System.Collections.Generic.List<string> KmsKeyIds { get { return this._kmsKeyIds; } set { this._kmsKeyIds = value; } } public bool IsSetKmsKeyIds () { return this._kmsKeyIds != null; } public AWS.Cryptography.MaterialProviders.IClientSupplier ClientSupplier { get { return this._clientSupplier; } set { this._clientSupplier = value; } } public bool IsSetClientSupplier () { return this._clientSupplier != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } public bool IsSetGrantTokens () { return this._grantTokens != null; } public void Validate() { } } }
44
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateAwsKmsMultiKeyringInput { private string _generator ; private System.Collections.Generic.List<string> _kmsKeyIds ; private AWS.Cryptography.MaterialProviders.IClientSupplier _clientSupplier ; private System.Collections.Generic.List<string> _grantTokens ; public string Generator { get { return this._generator; } set { this._generator = value; } } public bool IsSetGenerator () { return this._generator != null; } public System.Collections.Generic.List<string> KmsKeyIds { get { return this._kmsKeyIds; } set { this._kmsKeyIds = value; } } public bool IsSetKmsKeyIds () { return this._kmsKeyIds != null; } public AWS.Cryptography.MaterialProviders.IClientSupplier ClientSupplier { get { return this._clientSupplier; } set { this._clientSupplier = value; } } public bool IsSetClientSupplier () { return this._clientSupplier != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } public bool IsSetGrantTokens () { return this._grantTokens != null; } public void Validate() { } } }
44
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateAwsKmsRsaKeyringInput { private System.IO.MemoryStream _publicKey ; private string _kmsKeyId ; private Amazon.KeyManagementService.EncryptionAlgorithmSpec _encryptionAlgorithm ; private Amazon.KeyManagementService.IAmazonKeyManagementService _kmsClient ; private System.Collections.Generic.List<string> _grantTokens ; public System.IO.MemoryStream PublicKey { get { return this._publicKey; } set { this._publicKey = value; } } public bool IsSetPublicKey () { return this._publicKey != null; } public string KmsKeyId { get { return this._kmsKeyId; } set { this._kmsKeyId = value; } } public bool IsSetKmsKeyId () { return this._kmsKeyId != null; } public Amazon.KeyManagementService.EncryptionAlgorithmSpec EncryptionAlgorithm { get { return this._encryptionAlgorithm; } set { this._encryptionAlgorithm = value; } } public bool IsSetEncryptionAlgorithm () { return this._encryptionAlgorithm != null; } public Amazon.KeyManagementService.IAmazonKeyManagementService KmsClient { get { return this._kmsClient; } set { this._kmsClient = value; } } public bool IsSetKmsClient () { return this._kmsClient != null; } public System.Collections.Generic.List<string> GrantTokens { get { return this._grantTokens; } set { this._grantTokens = value; } } public bool IsSetGrantTokens () { return this._grantTokens != null; } public void Validate() { if (!IsSetKmsKeyId()) throw new System.ArgumentException("Missing value for required property 'KmsKeyId'"); if (!IsSetEncryptionAlgorithm()) throw new System.ArgumentException("Missing value for required property 'EncryptionAlgorithm'"); } } }
54
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateCryptographicMaterialsCacheInput { private int? _entryCapacity ; private int? _entryPruningTailSize ; public int EntryCapacity { get { return this._entryCapacity.GetValueOrDefault(); } set { this._entryCapacity = value; } } public bool IsSetEntryCapacity () { return this._entryCapacity.HasValue; } public int EntryPruningTailSize { get { return this._entryPruningTailSize.GetValueOrDefault(); } set { this._entryPruningTailSize = value; } } public bool IsSetEntryPruningTailSize () { return this._entryPruningTailSize.HasValue; } public void Validate() { if (!IsSetEntryCapacity()) throw new System.ArgumentException("Missing value for required property 'EntryCapacity'"); } } }
29
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateDefaultClientSupplierInput { public void Validate() { } } }
14
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateDefaultCryptographicMaterialsManagerInput { private AWS.Cryptography.MaterialProviders.IKeyring _keyring ; public AWS.Cryptography.MaterialProviders.IKeyring Keyring { get { return this._keyring; } set { this._keyring = value; } } public bool IsSetKeyring () { return this._keyring != null; } public void Validate() { if (!IsSetKeyring()) throw new System.ArgumentException("Missing value for required property 'Keyring'"); } } }
21
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateMultiKeyringInput { private AWS.Cryptography.MaterialProviders.IKeyring _generator ; private System.Collections.Generic.List<AWS.Cryptography.MaterialProviders.IKeyring> _childKeyrings ; public AWS.Cryptography.MaterialProviders.IKeyring Generator { get { return this._generator; } set { this._generator = value; } } public bool IsSetGenerator () { return this._generator != null; } public System.Collections.Generic.List<AWS.Cryptography.MaterialProviders.IKeyring> ChildKeyrings { get { return this._childKeyrings; } set { this._childKeyrings = value; } } public bool IsSetChildKeyrings () { return this._childKeyrings != null; } public void Validate() { if (!IsSetChildKeyrings()) throw new System.ArgumentException("Missing value for required property 'ChildKeyrings'"); } } }
29
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateRawAesKeyringInput { private string _keyNamespace ; private string _keyName ; private System.IO.MemoryStream _wrappingKey ; private AWS.Cryptography.MaterialProviders.AesWrappingAlg _wrappingAlg ; public string KeyNamespace { get { return this._keyNamespace; } set { this._keyNamespace = value; } } public bool IsSetKeyNamespace () { return this._keyNamespace != null; } public string KeyName { get { return this._keyName; } set { this._keyName = value; } } public bool IsSetKeyName () { return this._keyName != null; } public System.IO.MemoryStream WrappingKey { get { return this._wrappingKey; } set { this._wrappingKey = value; } } public bool IsSetWrappingKey () { return this._wrappingKey != null; } public AWS.Cryptography.MaterialProviders.AesWrappingAlg WrappingAlg { get { return this._wrappingAlg; } set { this._wrappingAlg = value; } } public bool IsSetWrappingAlg () { return this._wrappingAlg != null; } public void Validate() { if (!IsSetKeyNamespace()) throw new System.ArgumentException("Missing value for required property 'KeyNamespace'"); if (!IsSetKeyName()) throw new System.ArgumentException("Missing value for required property 'KeyName'"); if (!IsSetWrappingKey()) throw new System.ArgumentException("Missing value for required property 'WrappingKey'"); if (!IsSetWrappingAlg()) throw new System.ArgumentException("Missing value for required property 'WrappingAlg'"); } } }
48
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateRawRsaKeyringInput { private string _keyNamespace ; private string _keyName ; private AWS.Cryptography.MaterialProviders.PaddingScheme _paddingScheme ; private System.IO.MemoryStream _publicKey ; private System.IO.MemoryStream _privateKey ; public string KeyNamespace { get { return this._keyNamespace; } set { this._keyNamespace = value; } } public bool IsSetKeyNamespace () { return this._keyNamespace != null; } public string KeyName { get { return this._keyName; } set { this._keyName = value; } } public bool IsSetKeyName () { return this._keyName != null; } public AWS.Cryptography.MaterialProviders.PaddingScheme PaddingScheme { get { return this._paddingScheme; } set { this._paddingScheme = value; } } public bool IsSetPaddingScheme () { return this._paddingScheme != null; } public System.IO.MemoryStream PublicKey { get { return this._publicKey; } set { this._publicKey = value; } } public bool IsSetPublicKey () { return this._publicKey != null; } public System.IO.MemoryStream PrivateKey { get { return this._privateKey; } set { this._privateKey = value; } } public bool IsSetPrivateKey () { return this._privateKey != null; } public void Validate() { if (!IsSetKeyNamespace()) throw new System.ArgumentException("Missing value for required property 'KeyNamespace'"); if (!IsSetKeyName()) throw new System.ArgumentException("Missing value for required property 'KeyName'"); if (!IsSetPaddingScheme()) throw new System.ArgumentException("Missing value for required property 'PaddingScheme'"); } } }
55
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class CreateRequiredEncryptionContextCMMInput { private AWS.Cryptography.MaterialProviders.ICryptographicMaterialsManager _underlyingCMM ; private AWS.Cryptography.MaterialProviders.IKeyring _keyring ; private System.Collections.Generic.List<string> _requiredEncryptionContextKeys ; public AWS.Cryptography.MaterialProviders.ICryptographicMaterialsManager UnderlyingCMM { get { return this._underlyingCMM; } set { this._underlyingCMM = value; } } public bool IsSetUnderlyingCMM () { return this._underlyingCMM != null; } public AWS.Cryptography.MaterialProviders.IKeyring Keyring { get { return this._keyring; } set { this._keyring = value; } } public bool IsSetKeyring () { return this._keyring != null; } public System.Collections.Generic.List<string> RequiredEncryptionContextKeys { get { return this._requiredEncryptionContextKeys; } set { this._requiredEncryptionContextKeys = value; } } public bool IsSetRequiredEncryptionContextKeys () { return this._requiredEncryptionContextKeys != null; } public void Validate() { if (!IsSetRequiredEncryptionContextKeys()) throw new System.ArgumentException("Missing value for required property 'RequiredEncryptionContextKeys'"); } } }
37
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using System.IO; using System.Collections.Generic; using AWS.Cryptography.MaterialProviders; using software.amazon.cryptography.materialproviders.internaldafny.types; namespace AWS.Cryptography.MaterialProviders { internal class CryptographicMaterialsCache : CryptographicMaterialsCacheBase { internal readonly software.amazon.cryptography.materialproviders.internaldafny.types.ICryptographicMaterialsCache _impl; internal CryptographicMaterialsCache(software.amazon.cryptography.materialproviders.internaldafny.types.ICryptographicMaterialsCache impl) { this._impl = impl; } protected override void _PutCacheEntry(AWS.Cryptography.MaterialProviders.PutCacheEntryInput input) { software.amazon.cryptography.materialproviders.internaldafny.types._IPutCacheEntryInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N17_materialProviders__S18_PutCacheEntryInput(input); Wrappers_Compile._IResult<_System._ITuple0, software.amazon.cryptography.materialproviders.internaldafny.types._IError> result = this._impl.PutCacheEntry(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); } protected override void _UpdateUsageMetadata(AWS.Cryptography.MaterialProviders.UpdateUsageMetadataInput input) { software.amazon.cryptography.materialproviders.internaldafny.types._IUpdateUsageMetadataInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N17_materialProviders__S24_UpdateUsageMetadataInput(input); Wrappers_Compile._IResult<_System._ITuple0, software.amazon.cryptography.materialproviders.internaldafny.types._IError> result = this._impl.UpdateUsageMetadata(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); } protected override AWS.Cryptography.MaterialProviders.GetCacheEntryOutput _GetCacheEntry(AWS.Cryptography.MaterialProviders.GetCacheEntryInput input) { software.amazon.cryptography.materialproviders.internaldafny.types._IGetCacheEntryInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N17_materialProviders__S18_GetCacheEntryInput(input); Wrappers_Compile._IResult<software.amazon.cryptography.materialproviders.internaldafny.types._IGetCacheEntryOutput, software.amazon.cryptography.materialproviders.internaldafny.types._IError> result = this._impl.GetCacheEntry(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); return TypeConversion.FromDafny_N3_aws__N12_cryptography__N17_materialProviders__S19_GetCacheEntryOutput(result.dtor_value); } protected override void _DeleteCacheEntry(AWS.Cryptography.MaterialProviders.DeleteCacheEntryInput input) { software.amazon.cryptography.materialproviders.internaldafny.types._IDeleteCacheEntryInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N17_materialProviders__S21_DeleteCacheEntryInput(input); Wrappers_Compile._IResult<_System._ITuple0, software.amazon.cryptography.materialproviders.internaldafny.types._IError> result = this._impl.DeleteCacheEntry(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); } } }
38
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public abstract class CryptographicMaterialsCacheBase : ICryptographicMaterialsCache { public void PutCacheEntry ( AWS.Cryptography.MaterialProviders.PutCacheEntryInput input ) { input.Validate(); _PutCacheEntry ( input ) ; } protected abstract void _PutCacheEntry ( AWS.Cryptography.MaterialProviders.PutCacheEntryInput input ) ; public AWS.Cryptography.MaterialProviders.GetCacheEntryOutput GetCacheEntry ( AWS.Cryptography.MaterialProviders.GetCacheEntryInput input ) { input.Validate(); return _GetCacheEntry ( input ) ; } protected abstract AWS.Cryptography.MaterialProviders.GetCacheEntryOutput _GetCacheEntry ( AWS.Cryptography.MaterialProviders.GetCacheEntryInput input ) ; public void UpdateUsageMetadata ( AWS.Cryptography.MaterialProviders.UpdateUsageMetadataInput input ) { input.Validate(); _UpdateUsageMetadata ( input ) ; } protected abstract void _UpdateUsageMetadata ( AWS.Cryptography.MaterialProviders.UpdateUsageMetadataInput input ) ; public void DeleteCacheEntry ( AWS.Cryptography.MaterialProviders.DeleteCacheEntryInput input ) { input.Validate(); _DeleteCacheEntry ( input ) ; } protected abstract void _DeleteCacheEntry ( AWS.Cryptography.MaterialProviders.DeleteCacheEntryInput input ) ; } }
29
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using System.IO; using System.Collections.Generic; using AWS.Cryptography.MaterialProviders; using software.amazon.cryptography.materialproviders.internaldafny.types; namespace AWS.Cryptography.MaterialProviders { internal class CryptographicMaterialsManager : CryptographicMaterialsManagerBase { internal readonly software.amazon.cryptography.materialproviders.internaldafny.types.ICryptographicMaterialsManager _impl; internal CryptographicMaterialsManager(software.amazon.cryptography.materialproviders.internaldafny.types.ICryptographicMaterialsManager impl) { this._impl = impl; } protected override AWS.Cryptography.MaterialProviders.GetEncryptionMaterialsOutput _GetEncryptionMaterials(AWS.Cryptography.MaterialProviders.GetEncryptionMaterialsInput input) { software.amazon.cryptography.materialproviders.internaldafny.types._IGetEncryptionMaterialsInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N17_materialProviders__S27_GetEncryptionMaterialsInput(input); Wrappers_Compile._IResult<software.amazon.cryptography.materialproviders.internaldafny.types._IGetEncryptionMaterialsOutput, software.amazon.cryptography.materialproviders.internaldafny.types._IError> result = this._impl.GetEncryptionMaterials(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); return TypeConversion.FromDafny_N3_aws__N12_cryptography__N17_materialProviders__S28_GetEncryptionMaterialsOutput(result.dtor_value); } protected override AWS.Cryptography.MaterialProviders.DecryptMaterialsOutput _DecryptMaterials(AWS.Cryptography.MaterialProviders.DecryptMaterialsInput input) { software.amazon.cryptography.materialproviders.internaldafny.types._IDecryptMaterialsInput internalInput = TypeConversion.ToDafny_N3_aws__N12_cryptography__N17_materialProviders__S21_DecryptMaterialsInput(input); Wrappers_Compile._IResult<software.amazon.cryptography.materialproviders.internaldafny.types._IDecryptMaterialsOutput, software.amazon.cryptography.materialproviders.internaldafny.types._IError> result = this._impl.DecryptMaterials(internalInput); if (result.is_Failure) throw TypeConversion.FromDafny_CommonError(result.dtor_error); return TypeConversion.FromDafny_N3_aws__N12_cryptography__N17_materialProviders__S22_DecryptMaterialsOutput(result.dtor_value); } } }
26
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public abstract class CryptographicMaterialsManagerBase : ICryptographicMaterialsManager { public AWS.Cryptography.MaterialProviders.GetEncryptionMaterialsOutput GetEncryptionMaterials ( AWS.Cryptography.MaterialProviders.GetEncryptionMaterialsInput input ) { input.Validate(); return _GetEncryptionMaterials ( input ) ; } protected abstract AWS.Cryptography.MaterialProviders.GetEncryptionMaterialsOutput _GetEncryptionMaterials ( AWS.Cryptography.MaterialProviders.GetEncryptionMaterialsInput input ) ; public AWS.Cryptography.MaterialProviders.DecryptMaterialsOutput DecryptMaterials ( AWS.Cryptography.MaterialProviders.DecryptMaterialsInput input ) { input.Validate(); return _DecryptMaterials ( input ) ; } protected abstract AWS.Cryptography.MaterialProviders.DecryptMaterialsOutput _DecryptMaterials ( AWS.Cryptography.MaterialProviders.DecryptMaterialsInput input ) ; } }
19
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { using Amazon.Runtime; public class DBEAlgorithmSuiteId : ConstantClass { public static readonly DBEAlgorithmSuiteId ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_SYMSIG_HMAC_SHA384 = new DBEAlgorithmSuiteId ("0x6700"); public static readonly DBEAlgorithmSuiteId ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384 = new DBEAlgorithmSuiteId ("0x6701"); public static readonly DBEAlgorithmSuiteId [] Values = { ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384_SYMSIG_HMAC_SHA384 , ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_SYMSIG_HMAC_SHA384 } ; public DBEAlgorithmSuiteId (string value) : base(value) {} } }
18
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { using Amazon.Runtime; public class DBECommitmentPolicy : ConstantClass { public static readonly DBECommitmentPolicy REQUIRE_ENCRYPT_REQUIRE_DECRYPT = new DBECommitmentPolicy ("REQUIRE_ENCRYPT_REQUIRE_DECRYPT"); public static readonly DBECommitmentPolicy [] Values = { REQUIRE_ENCRYPT_REQUIRE_DECRYPT } ; public DBECommitmentPolicy (string value) : base(value) {} } }
16
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class DecryptionMaterials { private AWS.Cryptography.MaterialProviders.AlgorithmSuiteInfo _algorithmSuite ; private System.Collections.Generic.Dictionary<string, string> _encryptionContext ; private System.Collections.Generic.List<string> _requiredEncryptionContextKeys ; private System.IO.MemoryStream _plaintextDataKey ; private System.IO.MemoryStream _verificationKey ; private System.IO.MemoryStream _symmetricSigningKey ; public AWS.Cryptography.MaterialProviders.AlgorithmSuiteInfo AlgorithmSuite { get { return this._algorithmSuite; } set { this._algorithmSuite = value; } } public bool IsSetAlgorithmSuite () { return this._algorithmSuite != null; } public System.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } public bool IsSetEncryptionContext () { return this._encryptionContext != null; } public System.Collections.Generic.List<string> RequiredEncryptionContextKeys { get { return this._requiredEncryptionContextKeys; } set { this._requiredEncryptionContextKeys = value; } } public bool IsSetRequiredEncryptionContextKeys () { return this._requiredEncryptionContextKeys != null; } public System.IO.MemoryStream PlaintextDataKey { get { return this._plaintextDataKey; } set { this._plaintextDataKey = value; } } public bool IsSetPlaintextDataKey () { return this._plaintextDataKey != null; } public System.IO.MemoryStream VerificationKey { get { return this._verificationKey; } set { this._verificationKey = value; } } public bool IsSetVerificationKey () { return this._verificationKey != null; } public System.IO.MemoryStream SymmetricSigningKey { get { return this._symmetricSigningKey; } set { this._symmetricSigningKey = value; } } public bool IsSetSymmetricSigningKey () { return this._symmetricSigningKey != null; } public void Validate() { if (!IsSetAlgorithmSuite()) throw new System.ArgumentException("Missing value for required property 'AlgorithmSuite'"); if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); if (!IsSetRequiredEncryptionContextKeys()) throw new System.ArgumentException("Missing value for required property 'RequiredEncryptionContextKeys'"); } } }
63
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class DecryptMaterialsInput { private AWS.Cryptography.MaterialProviders.AlgorithmSuiteId _algorithmSuiteId ; private AWS.Cryptography.MaterialProviders.CommitmentPolicy _commitmentPolicy ; private System.Collections.Generic.List<AWS.Cryptography.MaterialProviders.EncryptedDataKey> _encryptedDataKeys ; private System.Collections.Generic.Dictionary<string, string> _encryptionContext ; private System.Collections.Generic.Dictionary<string, string> _reproducedEncryptionContext ; public AWS.Cryptography.MaterialProviders.AlgorithmSuiteId AlgorithmSuiteId { get { return this._algorithmSuiteId; } set { this._algorithmSuiteId = value; } } public bool IsSetAlgorithmSuiteId () { return this._algorithmSuiteId != null; } public AWS.Cryptography.MaterialProviders.CommitmentPolicy CommitmentPolicy { get { return this._commitmentPolicy; } set { this._commitmentPolicy = value; } } public bool IsSetCommitmentPolicy () { return this._commitmentPolicy != null; } public System.Collections.Generic.List<AWS.Cryptography.MaterialProviders.EncryptedDataKey> EncryptedDataKeys { get { return this._encryptedDataKeys; } set { this._encryptedDataKeys = value; } } public bool IsSetEncryptedDataKeys () { return this._encryptedDataKeys != null; } public System.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } public bool IsSetEncryptionContext () { return this._encryptionContext != null; } public System.Collections.Generic.Dictionary<string, string> ReproducedEncryptionContext { get { return this._reproducedEncryptionContext; } set { this._reproducedEncryptionContext = value; } } public bool IsSetReproducedEncryptionContext () { return this._reproducedEncryptionContext != null; } public void Validate() { if (!IsSetAlgorithmSuiteId()) throw new System.ArgumentException("Missing value for required property 'AlgorithmSuiteId'"); if (!IsSetCommitmentPolicy()) throw new System.ArgumentException("Missing value for required property 'CommitmentPolicy'"); if (!IsSetEncryptedDataKeys()) throw new System.ArgumentException("Missing value for required property 'EncryptedDataKeys'"); if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); } } }
56
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class DecryptMaterialsOutput { private AWS.Cryptography.MaterialProviders.DecryptionMaterials _decryptionMaterials ; public AWS.Cryptography.MaterialProviders.DecryptionMaterials DecryptionMaterials { get { return this._decryptionMaterials; } set { this._decryptionMaterials = value; } } public bool IsSetDecryptionMaterials () { return this._decryptionMaterials != null; } public void Validate() { if (!IsSetDecryptionMaterials()) throw new System.ArgumentException("Missing value for required property 'DecryptionMaterials'"); } } }
21
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class DeleteCacheEntryInput { private System.IO.MemoryStream _identifier ; public System.IO.MemoryStream Identifier { get { return this._identifier; } set { this._identifier = value; } } public bool IsSetIdentifier () { return this._identifier != null; } public void Validate() { if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); } } }
21
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class DerivationAlgorithm { private AWS.Cryptography.MaterialProviders.HKDF _hKDF ; private AWS.Cryptography.MaterialProviders.IDENTITY _iDENTITY ; private AWS.Cryptography.MaterialProviders.None _none ; public AWS.Cryptography.MaterialProviders.HKDF HKDF { get { return this._hKDF; } set { this._hKDF = value; } } public bool IsSetHKDF () { return this._hKDF != null; } public AWS.Cryptography.MaterialProviders.IDENTITY IDENTITY { get { return this._iDENTITY; } set { this._iDENTITY = value; } } public bool IsSetIDENTITY () { return this._iDENTITY != null; } public AWS.Cryptography.MaterialProviders.None None { get { return this._none; } set { this._none = value; } } public bool IsSetNone () { return this._none != null; } public void Validate() { var numberOfPropertiesSet = Convert.ToUInt16(IsSetHKDF()) + Convert.ToUInt16(IsSetIDENTITY()) + Convert.ToUInt16(IsSetNone()) ; if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); } } }
42
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class DIRECT_KEY_WRAPPING { public void Validate() { } } }
14
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class DiscoveryFilter { private System.Collections.Generic.List<string> _accountIds ; private string _partition ; public System.Collections.Generic.List<string> AccountIds { get { return this._accountIds; } set { this._accountIds = value; } } public bool IsSetAccountIds () { return this._accountIds != null; } public string Partition { get { return this._partition; } set { this._partition = value; } } public bool IsSetPartition () { return this._partition != null; } public void Validate() { if (!IsSetAccountIds()) throw new System.ArgumentException("Missing value for required property 'AccountIds'"); if (!IsSetPartition()) throw new System.ArgumentException("Missing value for required property 'Partition'"); } } }
30
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class ECDSA { private AWS.Cryptography.Primitives.ECDSASignatureAlgorithm _curve ; public AWS.Cryptography.Primitives.ECDSASignatureAlgorithm Curve { get { return this._curve; } set { this._curve = value; } } public bool IsSetCurve () { return this._curve != null; } public void Validate() { if (!IsSetCurve()) throw new System.ArgumentException("Missing value for required property 'Curve'"); } } }
21
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class EdkWrappingAlgorithm { private AWS.Cryptography.MaterialProviders.DIRECT_KEY_WRAPPING _dIRECT_KEY_WRAPPING ; private AWS.Cryptography.MaterialProviders.IntermediateKeyWrapping _intermediateKeyWrapping ; public AWS.Cryptography.MaterialProviders.DIRECT_KEY_WRAPPING DIRECT__KEY__WRAPPING { get { return this._dIRECT_KEY_WRAPPING; } set { this._dIRECT_KEY_WRAPPING = value; } } public bool IsSetDIRECT__KEY__WRAPPING () { return this._dIRECT_KEY_WRAPPING != null; } public AWS.Cryptography.MaterialProviders.IntermediateKeyWrapping IntermediateKeyWrapping { get { return this._intermediateKeyWrapping; } set { this._intermediateKeyWrapping = value; } } public bool IsSetIntermediateKeyWrapping () { return this._intermediateKeyWrapping != null; } public void Validate() { var numberOfPropertiesSet = Convert.ToUInt16(IsSetDIRECT__KEY__WRAPPING()) + Convert.ToUInt16(IsSetIntermediateKeyWrapping()) ; if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); } } }
33
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class Encrypt { private AWS.Cryptography.Primitives.AES_GCM _aES_GCM ; public AWS.Cryptography.Primitives.AES_GCM AES__GCM { get { return this._aES_GCM; } set { this._aES_GCM = value; } } public bool IsSetAES__GCM () { return this._aES_GCM != null; } public void Validate() { var numberOfPropertiesSet = Convert.ToUInt16(IsSetAES__GCM()) ; if (numberOfPropertiesSet == 0) throw new System.ArgumentException("No union value set"); if (numberOfPropertiesSet > 1) throw new System.ArgumentException("Multiple union values set"); } } }
24
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class EncryptedDataKey { private string _keyProviderId ; private System.IO.MemoryStream _keyProviderInfo ; private System.IO.MemoryStream _ciphertext ; public string KeyProviderId { get { return this._keyProviderId; } set { this._keyProviderId = value; } } public bool IsSetKeyProviderId () { return this._keyProviderId != null; } public System.IO.MemoryStream KeyProviderInfo { get { return this._keyProviderInfo; } set { this._keyProviderInfo = value; } } public bool IsSetKeyProviderInfo () { return this._keyProviderInfo != null; } public System.IO.MemoryStream Ciphertext { get { return this._ciphertext; } set { this._ciphertext = value; } } public bool IsSetCiphertext () { return this._ciphertext != null; } public void Validate() { if (!IsSetKeyProviderId()) throw new System.ArgumentException("Missing value for required property 'KeyProviderId'"); if (!IsSetKeyProviderInfo()) throw new System.ArgumentException("Missing value for required property 'KeyProviderInfo'"); if (!IsSetCiphertext()) throw new System.ArgumentException("Missing value for required property 'Ciphertext'"); } } }
39
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class EncryptionMaterials { private AWS.Cryptography.MaterialProviders.AlgorithmSuiteInfo _algorithmSuite ; private System.Collections.Generic.Dictionary<string, string> _encryptionContext ; private System.Collections.Generic.List<AWS.Cryptography.MaterialProviders.EncryptedDataKey> _encryptedDataKeys ; private System.Collections.Generic.List<string> _requiredEncryptionContextKeys ; private System.IO.MemoryStream _plaintextDataKey ; private System.IO.MemoryStream _signingKey ; private System.Collections.Generic.List<System.IO.MemoryStream> _symmetricSigningKeys ; public AWS.Cryptography.MaterialProviders.AlgorithmSuiteInfo AlgorithmSuite { get { return this._algorithmSuite; } set { this._algorithmSuite = value; } } public bool IsSetAlgorithmSuite () { return this._algorithmSuite != null; } public System.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } public bool IsSetEncryptionContext () { return this._encryptionContext != null; } public System.Collections.Generic.List<AWS.Cryptography.MaterialProviders.EncryptedDataKey> EncryptedDataKeys { get { return this._encryptedDataKeys; } set { this._encryptedDataKeys = value; } } public bool IsSetEncryptedDataKeys () { return this._encryptedDataKeys != null; } public System.Collections.Generic.List<string> RequiredEncryptionContextKeys { get { return this._requiredEncryptionContextKeys; } set { this._requiredEncryptionContextKeys = value; } } public bool IsSetRequiredEncryptionContextKeys () { return this._requiredEncryptionContextKeys != null; } public System.IO.MemoryStream PlaintextDataKey { get { return this._plaintextDataKey; } set { this._plaintextDataKey = value; } } public bool IsSetPlaintextDataKey () { return this._plaintextDataKey != null; } public System.IO.MemoryStream SigningKey { get { return this._signingKey; } set { this._signingKey = value; } } public bool IsSetSigningKey () { return this._signingKey != null; } public System.Collections.Generic.List<System.IO.MemoryStream> SymmetricSigningKeys { get { return this._symmetricSigningKeys; } set { this._symmetricSigningKeys = value; } } public bool IsSetSymmetricSigningKeys () { return this._symmetricSigningKeys != null; } public void Validate() { if (!IsSetAlgorithmSuite()) throw new System.ArgumentException("Missing value for required property 'AlgorithmSuite'"); if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); if (!IsSetEncryptedDataKeys()) throw new System.ArgumentException("Missing value for required property 'EncryptedDataKeys'"); if (!IsSetRequiredEncryptionContextKeys()) throw new System.ArgumentException("Missing value for required property 'RequiredEncryptionContextKeys'"); } } }
72
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class EntryAlreadyExists : Exception { public EntryAlreadyExists(string message) : base(message) {} } }
10
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class EntryDoesNotExist : Exception { public EntryDoesNotExist(string message) : base(message) {} } }
10
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { using Amazon.Runtime; public class ESDKAlgorithmSuiteId : ConstantClass { public static readonly ESDKAlgorithmSuiteId ALG_AES_128_GCM_IV12_TAG16_NO_KDF = new ESDKAlgorithmSuiteId ("0x0014"); public static readonly ESDKAlgorithmSuiteId ALG_AES_192_GCM_IV12_TAG16_NO_KDF = new ESDKAlgorithmSuiteId ("0x0046"); public static readonly ESDKAlgorithmSuiteId ALG_AES_256_GCM_IV12_TAG16_NO_KDF = new ESDKAlgorithmSuiteId ("0x0078"); public static readonly ESDKAlgorithmSuiteId ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256 = new ESDKAlgorithmSuiteId ("0x0114"); public static readonly ESDKAlgorithmSuiteId ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256 = new ESDKAlgorithmSuiteId ("0x0146"); public static readonly ESDKAlgorithmSuiteId ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256 = new ESDKAlgorithmSuiteId ("0x0178"); public static readonly ESDKAlgorithmSuiteId ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 = new ESDKAlgorithmSuiteId ("0x0214"); public static readonly ESDKAlgorithmSuiteId ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 = new ESDKAlgorithmSuiteId ("0x0346"); public static readonly ESDKAlgorithmSuiteId ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 = new ESDKAlgorithmSuiteId ("0x0378"); public static readonly ESDKAlgorithmSuiteId ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY = new ESDKAlgorithmSuiteId ("0x0478"); public static readonly ESDKAlgorithmSuiteId ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 = new ESDKAlgorithmSuiteId ("0x0578"); public static readonly ESDKAlgorithmSuiteId [] Values = { ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256 , ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256_ECDSA_P256 , ALG_AES_128_GCM_IV12_TAG16_NO_KDF , ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA256 , ALG_AES_192_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 , ALG_AES_192_GCM_IV12_TAG16_NO_KDF , ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY , ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY_ECDSA_P384 , ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA256 , ALG_AES_256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384 , ALG_AES_256_GCM_IV12_TAG16_NO_KDF } ; public ESDKAlgorithmSuiteId (string value) : base(value) {} } }
36
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { using Amazon.Runtime; public class ESDKCommitmentPolicy : ConstantClass { public static readonly ESDKCommitmentPolicy FORBID_ENCRYPT_ALLOW_DECRYPT = new ESDKCommitmentPolicy ("FORBID_ENCRYPT_ALLOW_DECRYPT"); public static readonly ESDKCommitmentPolicy REQUIRE_ENCRYPT_ALLOW_DECRYPT = new ESDKCommitmentPolicy ("REQUIRE_ENCRYPT_ALLOW_DECRYPT"); public static readonly ESDKCommitmentPolicy REQUIRE_ENCRYPT_REQUIRE_DECRYPT = new ESDKCommitmentPolicy ("REQUIRE_ENCRYPT_REQUIRE_DECRYPT"); public static readonly ESDKCommitmentPolicy [] Values = { FORBID_ENCRYPT_ALLOW_DECRYPT , REQUIRE_ENCRYPT_ALLOW_DECRYPT , REQUIRE_ENCRYPT_REQUIRE_DECRYPT } ; public ESDKCommitmentPolicy (string value) : base(value) {} } }
20
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class GetBranchKeyIdInput { private System.Collections.Generic.Dictionary<string, string> _encryptionContext ; public System.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } public bool IsSetEncryptionContext () { return this._encryptionContext != null; } public void Validate() { if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); } } }
21
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class GetBranchKeyIdOutput { private string _branchKeyId ; public string BranchKeyId { get { return this._branchKeyId; } set { this._branchKeyId = value; } } public bool IsSetBranchKeyId () { return this._branchKeyId != null; } public void Validate() { if (!IsSetBranchKeyId()) throw new System.ArgumentException("Missing value for required property 'BranchKeyId'"); } } }
21
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class GetCacheEntryInput { private System.IO.MemoryStream _identifier ; private long? _bytesUsed ; public System.IO.MemoryStream Identifier { get { return this._identifier; } set { this._identifier = value; } } public bool IsSetIdentifier () { return this._identifier != null; } public long BytesUsed { get { return this._bytesUsed.GetValueOrDefault(); } set { this._bytesUsed = value; } } public bool IsSetBytesUsed () { return this._bytesUsed.HasValue; } public void Validate() { if (!IsSetIdentifier()) throw new System.ArgumentException("Missing value for required property 'Identifier'"); } } }
29
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class GetCacheEntryOutput { private AWS.Cryptography.MaterialProviders.Materials _materials ; private long? _creationTime ; private long? _expiryTime ; private int? _messagesUsed ; private int? _bytesUsed ; public AWS.Cryptography.MaterialProviders.Materials Materials { get { return this._materials; } set { this._materials = value; } } public bool IsSetMaterials () { return this._materials != null; } public long CreationTime { get { return this._creationTime.GetValueOrDefault(); } set { this._creationTime = value; } } public bool IsSetCreationTime () { return this._creationTime.HasValue; } public long ExpiryTime { get { return this._expiryTime.GetValueOrDefault(); } set { this._expiryTime = value; } } public bool IsSetExpiryTime () { return this._expiryTime.HasValue; } public int MessagesUsed { get { return this._messagesUsed.GetValueOrDefault(); } set { this._messagesUsed = value; } } public bool IsSetMessagesUsed () { return this._messagesUsed.HasValue; } public int BytesUsed { get { return this._bytesUsed.GetValueOrDefault(); } set { this._bytesUsed = value; } } public bool IsSetBytesUsed () { return this._bytesUsed.HasValue; } public void Validate() { if (!IsSetMaterials()) throw new System.ArgumentException("Missing value for required property 'Materials'"); if (!IsSetCreationTime()) throw new System.ArgumentException("Missing value for required property 'CreationTime'"); if (!IsSetExpiryTime()) throw new System.ArgumentException("Missing value for required property 'ExpiryTime'"); if (!IsSetMessagesUsed()) throw new System.ArgumentException("Missing value for required property 'MessagesUsed'"); if (!IsSetBytesUsed()) throw new System.ArgumentException("Missing value for required property 'BytesUsed'"); } } }
57
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class GetClientInput { private string _region ; public string Region { get { return this._region; } set { this._region = value; } } public bool IsSetRegion () { return this._region != null; } public void Validate() { if (!IsSetRegion()) throw new System.ArgumentException("Missing value for required property 'Region'"); } } }
21
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class GetEncryptionMaterialsInput { private System.Collections.Generic.Dictionary<string, string> _encryptionContext ; private AWS.Cryptography.MaterialProviders.CommitmentPolicy _commitmentPolicy ; private AWS.Cryptography.MaterialProviders.AlgorithmSuiteId _algorithmSuiteId ; private long? _maxPlaintextLength ; private System.Collections.Generic.List<string> _requiredEncryptionContextKeys ; public System.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } public bool IsSetEncryptionContext () { return this._encryptionContext != null; } public AWS.Cryptography.MaterialProviders.CommitmentPolicy CommitmentPolicy { get { return this._commitmentPolicy; } set { this._commitmentPolicy = value; } } public bool IsSetCommitmentPolicy () { return this._commitmentPolicy != null; } public AWS.Cryptography.MaterialProviders.AlgorithmSuiteId AlgorithmSuiteId { get { return this._algorithmSuiteId; } set { this._algorithmSuiteId = value; } } public bool IsSetAlgorithmSuiteId () { return this._algorithmSuiteId != null; } public long MaxPlaintextLength { get { return this._maxPlaintextLength.GetValueOrDefault(); } set { this._maxPlaintextLength = value; } } public bool IsSetMaxPlaintextLength () { return this._maxPlaintextLength.HasValue; } public System.Collections.Generic.List<string> RequiredEncryptionContextKeys { get { return this._requiredEncryptionContextKeys; } set { this._requiredEncryptionContextKeys = value; } } public bool IsSetRequiredEncryptionContextKeys () { return this._requiredEncryptionContextKeys != null; } public void Validate() { if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); if (!IsSetCommitmentPolicy()) throw new System.ArgumentException("Missing value for required property 'CommitmentPolicy'"); } } }
54
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class GetEncryptionMaterialsOutput { private AWS.Cryptography.MaterialProviders.EncryptionMaterials _encryptionMaterials ; public AWS.Cryptography.MaterialProviders.EncryptionMaterials EncryptionMaterials { get { return this._encryptionMaterials; } set { this._encryptionMaterials = value; } } public bool IsSetEncryptionMaterials () { return this._encryptionMaterials != null; } public void Validate() { if (!IsSetEncryptionMaterials()) throw new System.ArgumentException("Missing value for required property 'EncryptionMaterials'"); } } }
21
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class HKDF { private AWS.Cryptography.Primitives.DigestAlgorithm _hmac ; private int? _saltLength ; private int? _inputKeyLength ; private int? _outputKeyLength ; public AWS.Cryptography.Primitives.DigestAlgorithm Hmac { get { return this._hmac; } set { this._hmac = value; } } public bool IsSetHmac () { return this._hmac != null; } public int SaltLength { get { return this._saltLength.GetValueOrDefault(); } set { this._saltLength = value; } } public bool IsSetSaltLength () { return this._saltLength.HasValue; } public int InputKeyLength { get { return this._inputKeyLength.GetValueOrDefault(); } set { this._inputKeyLength = value; } } public bool IsSetInputKeyLength () { return this._inputKeyLength.HasValue; } public int OutputKeyLength { get { return this._outputKeyLength.GetValueOrDefault(); } set { this._outputKeyLength = value; } } public bool IsSetOutputKeyLength () { return this._outputKeyLength.HasValue; } public void Validate() { if (!IsSetHmac()) throw new System.ArgumentException("Missing value for required property 'Hmac'"); if (!IsSetSaltLength()) throw new System.ArgumentException("Missing value for required property 'SaltLength'"); if (!IsSetInputKeyLength()) throw new System.ArgumentException("Missing value for required property 'InputKeyLength'"); if (!IsSetOutputKeyLength()) throw new System.ArgumentException("Missing value for required property 'OutputKeyLength'"); } } }
48
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public interface IBranchKeyIdSupplier { AWS.Cryptography.MaterialProviders.GetBranchKeyIdOutput GetBranchKeyId ( AWS.Cryptography.MaterialProviders.GetBranchKeyIdInput input ) ; } }
10
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public interface IClientSupplier { Amazon.KeyManagementService.IAmazonKeyManagementService GetClient ( AWS.Cryptography.MaterialProviders.GetClientInput input ) ; } }
10
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public interface ICryptographicMaterialsCache { void PutCacheEntry ( AWS.Cryptography.MaterialProviders.PutCacheEntryInput input ) ; AWS.Cryptography.MaterialProviders.GetCacheEntryOutput GetCacheEntry ( AWS.Cryptography.MaterialProviders.GetCacheEntryInput input ) ; void UpdateUsageMetadata ( AWS.Cryptography.MaterialProviders.UpdateUsageMetadataInput input ) ; void DeleteCacheEntry ( AWS.Cryptography.MaterialProviders.DeleteCacheEntryInput input ) ; } }
13
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public interface ICryptographicMaterialsManager { AWS.Cryptography.MaterialProviders.GetEncryptionMaterialsOutput GetEncryptionMaterials ( AWS.Cryptography.MaterialProviders.GetEncryptionMaterialsInput input ) ; AWS.Cryptography.MaterialProviders.DecryptMaterialsOutput DecryptMaterials ( AWS.Cryptography.MaterialProviders.DecryptMaterialsInput input ) ; } }
11
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class IDENTITY { public void Validate() { } } }
14
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public interface IKeyring { AWS.Cryptography.MaterialProviders.OnEncryptOutput OnEncrypt ( AWS.Cryptography.MaterialProviders.OnEncryptInput input ) ; AWS.Cryptography.MaterialProviders.OnDecryptOutput OnDecrypt ( AWS.Cryptography.MaterialProviders.OnDecryptInput input ) ; } }
11
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class InitializeDecryptionMaterialsInput { private AWS.Cryptography.MaterialProviders.AlgorithmSuiteId _algorithmSuiteId ; private System.Collections.Generic.Dictionary<string, string> _encryptionContext ; private System.Collections.Generic.List<string> _requiredEncryptionContextKeys ; public AWS.Cryptography.MaterialProviders.AlgorithmSuiteId AlgorithmSuiteId { get { return this._algorithmSuiteId; } set { this._algorithmSuiteId = value; } } public bool IsSetAlgorithmSuiteId () { return this._algorithmSuiteId != null; } public System.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } public bool IsSetEncryptionContext () { return this._encryptionContext != null; } public System.Collections.Generic.List<string> RequiredEncryptionContextKeys { get { return this._requiredEncryptionContextKeys; } set { this._requiredEncryptionContextKeys = value; } } public bool IsSetRequiredEncryptionContextKeys () { return this._requiredEncryptionContextKeys != null; } public void Validate() { if (!IsSetAlgorithmSuiteId()) throw new System.ArgumentException("Missing value for required property 'AlgorithmSuiteId'"); if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); if (!IsSetRequiredEncryptionContextKeys()) throw new System.ArgumentException("Missing value for required property 'RequiredEncryptionContextKeys'"); } } }
39
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class InitializeEncryptionMaterialsInput { private AWS.Cryptography.MaterialProviders.AlgorithmSuiteId _algorithmSuiteId ; private System.Collections.Generic.Dictionary<string, string> _encryptionContext ; private System.Collections.Generic.List<string> _requiredEncryptionContextKeys ; private System.IO.MemoryStream _signingKey ; private System.IO.MemoryStream _verificationKey ; public AWS.Cryptography.MaterialProviders.AlgorithmSuiteId AlgorithmSuiteId { get { return this._algorithmSuiteId; } set { this._algorithmSuiteId = value; } } public bool IsSetAlgorithmSuiteId () { return this._algorithmSuiteId != null; } public System.Collections.Generic.Dictionary<string, string> EncryptionContext { get { return this._encryptionContext; } set { this._encryptionContext = value; } } public bool IsSetEncryptionContext () { return this._encryptionContext != null; } public System.Collections.Generic.List<string> RequiredEncryptionContextKeys { get { return this._requiredEncryptionContextKeys; } set { this._requiredEncryptionContextKeys = value; } } public bool IsSetRequiredEncryptionContextKeys () { return this._requiredEncryptionContextKeys != null; } public System.IO.MemoryStream SigningKey { get { return this._signingKey; } set { this._signingKey = value; } } public bool IsSetSigningKey () { return this._signingKey != null; } public System.IO.MemoryStream VerificationKey { get { return this._verificationKey; } set { this._verificationKey = value; } } public bool IsSetVerificationKey () { return this._verificationKey != null; } public void Validate() { if (!IsSetAlgorithmSuiteId()) throw new System.ArgumentException("Missing value for required property 'AlgorithmSuiteId'"); if (!IsSetEncryptionContext()) throw new System.ArgumentException("Missing value for required property 'EncryptionContext'"); if (!IsSetRequiredEncryptionContextKeys()) throw new System.ArgumentException("Missing value for required property 'RequiredEncryptionContextKeys'"); } } }
55
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class IntermediateKeyWrapping { private AWS.Cryptography.MaterialProviders.DerivationAlgorithm _keyEncryptionKeyKdf ; private AWS.Cryptography.MaterialProviders.DerivationAlgorithm _macKeyKdf ; private AWS.Cryptography.MaterialProviders.Encrypt _pdkEncryptAlgorithm ; public AWS.Cryptography.MaterialProviders.DerivationAlgorithm KeyEncryptionKeyKdf { get { return this._keyEncryptionKeyKdf; } set { this._keyEncryptionKeyKdf = value; } } public bool IsSetKeyEncryptionKeyKdf () { return this._keyEncryptionKeyKdf != null; } public AWS.Cryptography.MaterialProviders.DerivationAlgorithm MacKeyKdf { get { return this._macKeyKdf; } set { this._macKeyKdf = value; } } public bool IsSetMacKeyKdf () { return this._macKeyKdf != null; } public AWS.Cryptography.MaterialProviders.Encrypt PdkEncryptAlgorithm { get { return this._pdkEncryptAlgorithm; } set { this._pdkEncryptAlgorithm = value; } } public bool IsSetPdkEncryptAlgorithm () { return this._pdkEncryptAlgorithm != null; } public void Validate() { if (!IsSetKeyEncryptionKeyKdf()) throw new System.ArgumentException("Missing value for required property 'KeyEncryptionKeyKdf'"); if (!IsSetMacKeyKdf()) throw new System.ArgumentException("Missing value for required property 'MacKeyKdf'"); if (!IsSetPdkEncryptAlgorithm()) throw new System.ArgumentException("Missing value for required property 'PdkEncryptAlgorithm'"); } } }
39
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class InvalidAlgorithmSuiteInfo : Exception { public InvalidAlgorithmSuiteInfo(string message) : base(message) {} } }
10
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class InvalidAlgorithmSuiteInfoOnDecrypt : Exception { public InvalidAlgorithmSuiteInfoOnDecrypt(string message) : base(message) {} } }
10
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class InvalidAlgorithmSuiteInfoOnEncrypt : Exception { public InvalidAlgorithmSuiteInfoOnEncrypt(string message) : base(message) {} } }
10
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class InvalidDecryptionMaterials : Exception { public InvalidDecryptionMaterials(string message) : base(message) {} } }
10
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class InvalidDecryptionMaterialsTransition : Exception { public InvalidDecryptionMaterialsTransition(string message) : base(message) {} } }
10
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class InvalidEncryptionMaterials : Exception { public InvalidEncryptionMaterials(string message) : base(message) {} } }
10
aws-cryptographic-material-providers-library-java
aws
C#
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Do not modify this file. This file is machine generated, and any changes to it will be overwritten. using System; using AWS.Cryptography.MaterialProviders; namespace AWS.Cryptography.MaterialProviders { public class InvalidEncryptionMaterialsTransition : Exception { public InvalidEncryptionMaterialsTransition(string message) : base(message) {} } }
10