private static AWSCredentials GetAWSCredentials(string profileName, ICredentialProfileSource profileSource,
                                                        CredentialProfileOptions options, RegionEndpoint stsRegion, bool nonCallbackOnly)
        {
            var profileType = CredentialProfileTypeDetector.DetectProfileType(options);

            if (nonCallbackOnly && profileType.HasValue && IsCallbackRequired(profileType.Value))
            {
                if (profileType == CredentialProfileType.AssumeRoleExternalMFA ||
                    profileType == CredentialProfileType.AssumeRoleMFA)
                {
                    var mfaMessage = profileName == null
                        ? "The credential options represent AssumeRoleAWSCredentials that require an MFA.  This is not allowed here.  " +
                                     "Please use credential options for AssumeRoleAWSCredentials that don't require an MFA, or a different type of credentials."
                        : String.Format(CultureInfo.InvariantCulture,
                                        "The profile [{0}] is an assume role profile that requires an MFA.  This type of profile is not allowed here.  " +
                                        "Please use an assume role profile that doesn't require an MFA, or a different type of profile.", profileName);
                    throw new InvalidOperationException(mfaMessage);
                }
#if BCL
                else if (profileType == CredentialProfileType.SAMLRoleUserIdentity)
                {
                    var samlMessage = profileName == null
                        ? "The credential options represent FederatedAWSCredentials that specify a user identity.  This is not allowed here.  " +
                                      "Please use credential options for FederatedAWSCredentials without an explicit user identity, or a different type of credentials."
                        : String.Format(CultureInfo.InvariantCulture,
                                        "The profile [{0}] is a SAML role profile that specifies a user identity.  This type of profile is not allowed here.  " +
                                        "Please use a SAML role profile without an explicit user identity, or a different type of profile.", profileName);
                    throw new InvalidOperationException(samlMessage);
                }
#endif
            }
            return(GetAWSCredentialsInternal(profileName, profileType, options, stsRegion, profileSource, true));
        }
        /// <summary>
        /// Return the credentials for the profile if valid credentials can created.
        /// </summary>
        /// <param name="options">The options to get AWSCredentials for.</param>
        /// <param name="profileSource">The profile source, for profiles that reference other profiles.</param>
        /// <param name="credentials">The credentials for the profile.</param>
        /// <returns>True if credentials can be created from the profile, false otherwise.</returns>
        public static bool TryGetAWSCredentials(CredentialProfileOptions options, ICredentialProfileSource profileSource, out AWSCredentials credentials)
        {
            var profileType = CredentialProfileTypeDetector.DetectProfileType(options);

            credentials = GetAWSCredentialsInternal(null, profileType, options, null, profileSource, false);
            return(credentials != null);
        }
        /// <summary>
        /// Construct a new CredentialProfile.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="profileOptions"></param>
        public CredentialProfile(string name, CredentialProfileOptions profileOptions)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Name must not be null or empty.");
            }
            if (profileOptions == null)
            {
                throw new ArgumentNullException("profileOptions");
            }

            Name    = name;
            Options = profileOptions;
        }
 /// <summary>
 /// Gets the AWSCredentials for this profile if CanCreateAWSCredentials is true
 /// and AWSCredentials can be created.  Throws an exception otherwise.
 ///
 /// See <see cref="CredentialProfileOptions"/> for a list of AWSCredentials returned by this method.
 /// </summary>
 /// <param name="options">The options to get AWSCredentials for.</param>
 /// <param name="profileSource">The profile source, for options that reference other profiles.</param>
 /// <param name="nonCallbackOnly">If true, throw a descriptive exception for any credentials that would not operate as-is.
 /// In other words, any credentials that require programmatic callbacks at runtime.</param>
 /// <returns>AWSCredentials for the options given.</returns>
 public static AWSCredentials GetAWSCredentials(CredentialProfileOptions options, ICredentialProfileSource profileSource, bool nonCallbackOnly)
 {
     return(GetAWSCredentials(null, profileSource, options, null, nonCallbackOnly));
 }
 /// <summary>
 /// Gets the AWSCredentials for this profile if CanCreateAWSCredentials is true
 /// and AWSCredentials can be created.  Throws an exception otherwise.
 ///
 /// See <see cref="CredentialProfileOptions"/> for a list of AWSCredentials returned by this method.
 /// </summary>
 /// <param name="options">The options to get AWSCredentials for.</param>
 /// <param name="profileSource">The profile source, for options that reference other profiles.</param>
 /// <returns>AWSCredentials for the options given.</returns>
 public static AWSCredentials GetAWSCredentials(CredentialProfileOptions options, ICredentialProfileSource profileSource)
 {
     return(GetAWSCredentials(null, profileSource, options, null, false));
 }
        private static AWSCredentials GetAWSCredentialsInternal(string profileName, CredentialProfileType?profileType,
                                                                CredentialProfileOptions options, RegionEndpoint stsRegion, ICredentialProfileSource profileSource, bool throwIfInvalid)
        {
            if (profileType.HasValue)
            {
                switch (profileType)
                {
                case CredentialProfileType.Basic:
                    return(new BasicAWSCredentials(options.AccessKey, options.SecretKey));

                case CredentialProfileType.Session:
                    return(new SessionAWSCredentials(options.AccessKey, options.SecretKey, options.Token));

                case CredentialProfileType.AssumeRole:
                case CredentialProfileType.AssumeRoleExternal:
                case CredentialProfileType.AssumeRoleMFA:
                case CredentialProfileType.AssumeRoleExternalMFA:
                    AWSCredentials sourceCredentials;
                    // get basic or session credentials from profileSource
                    try
                    {
                        sourceCredentials = GetSourceAWSCredentials(options.SourceProfile, profileSource, throwIfInvalid);
                    }
                    catch (InvalidDataException e)
                    {
                        var sourceMessage = profileName == null
                               ? string.Format(CultureInfo.InvariantCulture,
                                               "Error reading source profile [{0}] for the credential options provided.", options.SourceProfile)
                               : string.Format(CultureInfo.InvariantCulture,
                                               "Error reading source profile [{0}] for profile [{1}].", options.SourceProfile, profileName);

                        return(ThrowOrReturnNull(sourceMessage, e, throwIfInvalid));
                    }

#pragma warning disable CS0612 // Type or member is obsolete
                    var roleSessionName = RoleSessionNamePrefix + AWSSDKUtils.CorrectedUtcNow.Ticks;
#pragma warning restore CS0612 // Type or member is obsolete
                    var assumeRoleOptions = new AssumeRoleAWSCredentialsOptions()
                    {
                        ExternalId      = options.ExternalID,
                        MfaSerialNumber = options.MfaSerial
                    };
                    return(new AssumeRoleAWSCredentials(sourceCredentials, options.RoleArn, roleSessionName, assumeRoleOptions));

                case CredentialProfileType.AssumeRoleCredentialSource:
                    // get credentials specified by credentialSource
                    try
                    {
                        sourceCredentials = GetCredentialSourceAWSCredentials(options.CredentialSource, throwIfInvalid);
                    }
                    catch (InvalidDataException e)
                    {
                        var sourceMessage = profileName == null
                               ? string.Format(CultureInfo.InvariantCulture,
                                               "Error reading credential source [{0}] for the credential options provided.", options.CredentialSource)
                               : string.Format(CultureInfo.InvariantCulture,
                                               "Error reading credential source [{0}] for profile [{1}].", options.CredentialSource, profileName);

                        return(ThrowOrReturnNull(sourceMessage, e, throwIfInvalid));
                    }

#pragma warning disable CS0612 // Type or member is obsolete
                    roleSessionName = RoleSessionNamePrefix + AWSSDKUtils.CorrectedUtcNow.Ticks;
#pragma warning restore CS0612 // Type or member is obsolete
                    assumeRoleOptions = new AssumeRoleAWSCredentialsOptions();
                    return(new AssumeRoleAWSCredentials(sourceCredentials, options.RoleArn, roleSessionName, assumeRoleOptions));

#if BCL
                case CredentialProfileType.SAMLRole:
                case CredentialProfileType.SAMLRoleUserIdentity:
                    if (UserCrypto.IsUserCryptAvailable)
                    {
                        var federatedOptions = new FederatedAWSCredentialsOptions()
                        {
                            STSRegion    = stsRegion,
                            UserIdentity = options.UserIdentity,
                            ProfileName  = profileName
                        };
                        return(new FederatedAWSCredentials(new SAMLEndpointManager().GetEndpoint(options.EndpointName),
                                                           options.RoleArn, federatedOptions));
                    }
                    else
                    {
                        return(ThrowOrReturnNull("Federated credentials are not available on this platform.", null, throwIfInvalid));
                    }
#endif
                default:
                    var defaultMessage = profileName == null
                            ? string.Format(CultureInfo.InvariantCulture,
                                            "Invalid ProfileType {0} for the credential options provided.", profileType)
                            : string.Format(CultureInfo.InvariantCulture,
                                            "Invalid ProfileType {0} for credential profile [{1}].", profileType, profileName);

                    return(ThrowOrReturnNull(defaultMessage, null, throwIfInvalid));
                }
            }
            else
            {
                return(ThrowInvalidOrReturnNull(profileName, throwIfInvalid));
            }
        }
Beispiel #7
0
        private static AWSCredentials GetAWSCredentialsInternal(
            string profileName,
            CredentialProfileType?profileType,
            CredentialProfileOptions options,
            RegionEndpoint stsRegion,
            ICredentialProfileSource profileSource,
            bool throwIfInvalid,
            HashSet <string> profileLoopAvoidance = null)
        {
            if (profileType.HasValue)
            {
                switch (profileType)
                {
                case CredentialProfileType.Basic:
                    return(new BasicAWSCredentials(options.AccessKey, options.SecretKey));

                case CredentialProfileType.Session:
                    return(new SessionAWSCredentials(options.AccessKey, options.SecretKey, options.Token));

                case CredentialProfileType.AssumeRole:
                case CredentialProfileType.AssumeRoleExternal:
                case CredentialProfileType.AssumeRoleMFA:
                case CredentialProfileType.AssumeRoleExternalMFA:
                case CredentialProfileType.AssumeRoleSessionName:
                case CredentialProfileType.AssumeRoleExternalSessionName:
                case CredentialProfileType.AssumeRoleMFASessionName:
                case CredentialProfileType.AssumeRoleExternalMFASessionName:
                    if (profileName != null)
                    {
                        if (profileLoopAvoidance == null)
                        {
                            profileLoopAvoidance = new HashSet <string>();
                        }
                        else if (profileLoopAvoidance.Contains(profileName))
                        {
                            var sourceMessage = string.Format(CultureInfo.InvariantCulture,
                                                              "Error reading profile [{0}]: the source profile definition is cyclical.", profileName);
                            return(ThrowOrReturnNull(sourceMessage, null, throwIfInvalid));
                        }
                        profileLoopAvoidance.Add(profileName);
                    }

                    AWSCredentials sourceCredentials;
                    try
                    {
                        sourceCredentials = GetSourceAWSCredentials(options.SourceProfile, profileSource, throwIfInvalid, profileLoopAvoidance);
                    }
                    catch (InvalidDataException e)
                    {
                        var sourceMessage = profileName == null
                               ? string.Format(CultureInfo.InvariantCulture,
                                               "Error reading source profile [{0}] for the credential options provided.", options.SourceProfile)
                               : string.Format(CultureInfo.InvariantCulture,
                                               "Error reading source profile [{0}] for profile [{1}].", options.SourceProfile, profileName);

                        return(ThrowOrReturnNull(sourceMessage, e, throwIfInvalid));
                    }

#pragma warning disable CS0612 // Type or member is obsolete
                    var roleSessionName = options.RoleSessionName ?? RoleSessionNamePrefix + AWSSDKUtils.CorrectedUtcNow.Ticks;
#pragma warning restore CS0612 // Type or member is obsolete
                    var assumeRoleOptions = new AssumeRoleAWSCredentialsOptions()
                    {
                        ExternalId      = options.ExternalID,
                        MfaSerialNumber = options.MfaSerial
                    };
                    return(new AssumeRoleAWSCredentials(sourceCredentials, options.RoleArn, roleSessionName, assumeRoleOptions));

                case CredentialProfileType.AssumeRoleCredentialSource:
                case CredentialProfileType.AssumeRoleCredentialSourceSessionName:
                    // get credentials specified by credentialSource
                    try
                    {
                        sourceCredentials = GetCredentialSourceAWSCredentials(options.CredentialSource, throwIfInvalid);
                    }
                    catch (InvalidDataException e)
                    {
                        var sourceMessage = profileName == null
                               ? string.Format(CultureInfo.InvariantCulture,
                                               "Error reading credential source [{0}] for the credential options provided.", options.CredentialSource)
                               : string.Format(CultureInfo.InvariantCulture,
                                               "Error reading credential source [{0}] for profile [{1}].", options.CredentialSource, profileName);

                        return(ThrowOrReturnNull(sourceMessage, e, throwIfInvalid));
                    }

#pragma warning disable CS0612 // Type or member is obsolete
                    roleSessionName = options.RoleSessionName ?? RoleSessionNamePrefix + AWSSDKUtils.CorrectedUtcNow.Ticks;
#pragma warning restore CS0612 // Type or member is obsolete
                    assumeRoleOptions = new AssumeRoleAWSCredentialsOptions();
                    return(new AssumeRoleAWSCredentials(sourceCredentials, options.RoleArn, roleSessionName, assumeRoleOptions));

                case CredentialProfileType.AssumeRoleWithWebIdentity:
                case CredentialProfileType.AssumeRoleWithWebIdentitySessionName:
                    return(new AssumeRoleWithWebIdentityCredentials(options.WebIdentityTokenFile, options.RoleArn, options.RoleSessionName));

#if !BCL35
                case CredentialProfileType.SSO:
                {
                    var ssoCredentialsOptions = new SSOAWSCredentialsOptions();
                    return(new SSOAWSCredentials(
                               options.SsoAccountId, options.SsoRegion,
                               options.SsoRoleName, options.SsoStartUrl,
                               ssoCredentialsOptions
                               ));
                }
#endif
                case CredentialProfileType.SAMLRole:
                case CredentialProfileType.SAMLRoleUserIdentity:
                    if (UserCrypto.IsUserCryptAvailable)
                    {
                        var federatedOptions = new FederatedAWSCredentialsOptions()
                        {
                            STSRegion    = stsRegion,
                            UserIdentity = options.UserIdentity,
                            ProfileName  = profileName
                        };
                        return(new FederatedAWSCredentials(new SAMLEndpointManager().GetEndpoint(options.EndpointName),
                                                           options.RoleArn, federatedOptions));
                    }
                    else
                    {
                        return(ThrowOrReturnNull("Federated credentials are not available on this platform.", null, throwIfInvalid));
                    }

                case CredentialProfileType.CredentialProcess:
                    return(new ProcessAWSCredentials(options.CredentialProcess));

                default:
                    var defaultMessage = profileName == null
                            ? string.Format(CultureInfo.InvariantCulture,
                                            "Invalid ProfileType {0} for the credential options provided.", profileType)
                            : string.Format(CultureInfo.InvariantCulture,
                                            "Invalid ProfileType {0} for credential profile [{1}].", profileType, profileName);

                    return(ThrowOrReturnNull(defaultMessage, null, throwIfInvalid));
                }
            }
            else
            {
                return(ThrowInvalidOrReturnNull(profileName, throwIfInvalid));
            }
        }
Beispiel #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Enable CORS.
            services.AddCors();

            // Add MVC service.
            services.AddMvc();

            // Create AWS Profile options for basic profile.
            var awsProfileOptions = new Amazon.Runtime.CredentialManagement.CredentialProfileOptions()
            {
                AccessKey = Configuration.GetValue <string>("Secrets:AWS:AccessKey"),
                SecretKey = Configuration.GetValue <string>("Secrets:AWS:AccessKeySecret"),
            };

            // Creates basic profile with above options, then set AWS region.
            var awsProfile = new Amazon.Runtime.CredentialManagement.CredentialProfile("basic-profile", awsProfileOptions);

            awsProfile.Region = RegionEndpoint.APNortheast2;

            // Registers AWS profile to AWS SDK's .NET SDK credentials file.
            var sdkFile = new NetSDKCredentialsFile();

            sdkFile.RegisterProfile(awsProfile);

            // Add AWS options.
            services.AddDefaultAWSOptions(new AWSOptions()
            {
                Region = RegionEndpoint.APNortheast2, Profile = awsProfile.Name
            });

            // Add DynamoDB service.
            services.AddAWSService <IAmazonDynamoDB>();

            // Add UserServices.
            // If want to use classic user service, use `UserService`.
            services.AddScoped <IUserService, DynamoDBUserService>();

            // Configure JWT authentication.
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false; // NOTE: This should be set to `true` on production.
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(Configuration.GetValue <string>("Secrets:JWT"))),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            // In production, the React files will be served from this directory
            // This code portion is not related to webpack_hmr.
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "wwwroot/dist";
            });
        }
Beispiel #9
0
        private static AWSCredentials GetAWSCredentialsInternal(string profileName, CredentialProfileType?profileType,
                                                                CredentialProfileOptions options, RegionEndpoint stsRegion, ICredentialProfileSource profileSource, bool throwIfInvalid)
        {
            if (profileType.HasValue)
            {
                switch (profileType)
                {
                case CredentialProfileType.Basic:
                    return(new BasicAWSCredentials(options.AccessKey, options.SecretKey));

                case CredentialProfileType.Session:
                    return(new SessionAWSCredentials(options.AccessKey, options.SecretKey, options.Token));

                case CredentialProfileType.AssumeRole:
                case CredentialProfileType.AssumeRoleExternal:
                case CredentialProfileType.AssumeRoleMFA:
                case CredentialProfileType.AssumeRoleExternalMFA:
                    BasicAWSCredentials sourceCredentials;
                    // get basic credentials from profileSource
                    try
                    {
                        sourceCredentials = GetSourceAWSCredentials(options.SourceProfile, profileSource, throwIfInvalid);
                    }
                    catch (InvalidDataException e)
                    {
                        var sourceMessage = profileName == null
                               ? string.Format(CultureInfo.InvariantCulture,
                                               "Error reading source profile [{0}] for the credential options provided.", options.SourceProfile)
                               : string.Format(CultureInfo.InvariantCulture,
                                               "Error reading source profile [{0}] for profile [{1}].", options.SourceProfile, profileName);

                        return(ThrowOrReturnNull(sourceMessage, e, throwIfInvalid));
                    }

                    var roleSessionName   = RoleSessionNamePrefix + DateTime.UtcNow.Ticks;
                    var assumeRoleOptions = new AssumeRoleAWSCredentialsOptions()
                    {
                        ExternalId      = options.ExternalID,
                        MfaSerialNumber = options.MfaSerial
                    };
                    return(new AssumeRoleAWSCredentials(sourceCredentials, options.RoleArn, roleSessionName, assumeRoleOptions));

#if BCL
                case CredentialProfileType.SAMLRole:
                case CredentialProfileType.SAMLRoleUserIdentity:
                    var federatedOptions = new FederatedAWSCredentialsOptions()
                    {
                        STSRegion    = stsRegion,
                        UserIdentity = options.UserIdentity,
                        ProfileName  = profileName
                    };
                    return(new FederatedAWSCredentials(EndpointManager.GetEndpoint(options.EndpointName),
                                                       options.RoleArn, federatedOptions));
#endif
                default:
                    var defaultMessage = profileName == null
                            ? string.Format(CultureInfo.InvariantCulture,
                                            "Invalid ProfileType {0} for the credential options provided.", profileType)
                            : string.Format(CultureInfo.InvariantCulture,
                                            "Invalid ProfileType {0} for credential profile [{1}].", profileType, profileName);

                    return(ThrowOrReturnNull(defaultMessage, null, throwIfInvalid));
                }
            }
            else
            {
                return(ThrowInvalidOrReturnNull(profileName, throwIfInvalid));
            }
        }