/// <summary>
        /// Creates an authentication token containing arbitrary auth data and the specified options.
        /// </summary>
        /// <param name="data">Arbitrary data that will be passed to the Firebase Rules API, once a client authenticates.  Must be able to be serialized to JSON with <see cref="System.Web.Script.Serialization.JavaScriptSerializer"/>.</param>
        /// <param name="options">A set of custom options for the token.</param>
        /// <returns>The auth token.</returns>
        public string CreateToken(IDictionary<string, object> data, TokenOptions options)
        {
            bool dataEmpty = (data == null || data.Count == 0);
            if (dataEmpty && (options == TokenOptions.Empty || (!options.Admin && !options.Debug)))
                throw new Exception(
                    "data is empty and no options are set.  This token will have no effect on Firebase.");

            var claims = new Dictionary<string, object>
            {
                ["v"] = TokenVersion,
                ["iat"] = SecondsSinceEpoch(DateTime.Now)
            };

            bool isAdminToken = (options != TokenOptions.Empty && options.Admin);
            ValidateToken(data, isAdminToken);

            if (!dataEmpty)
                claims["d"] = data;

            // Handle options.
            if (options != TokenOptions.Empty)
            {
                if (options.Expires.HasValue)
                    claims["exp"] = SecondsSinceEpoch(options.Expires.Value);
                if (options.NotBefore.HasValue)
                    claims["nbf"] = SecondsSinceEpoch(options.NotBefore.Value);
                if (options.Admin)
                    claims["admin"] = true;
                if (options.Debug)
                    claims["debug"] = true;
            }

            string token = ComputeToken(claims);
            if (token.Length > 1024)
                throw new Exception("Generated token is too long. The token cannot be longer than 1024 bytes.");

            return token;
        }
        /// <summary>
        /// Create a token generator instance
        /// </summary>
        /// <param name="tokenOptions"></param>

        public JwtTokenGenerator(TokenOptions tokenOptions)
        {
            this.tokenOptions = tokenOptions ??
                                throw new ArgumentNullException(
                                          $"An instance of valid {nameof(TokenOptions)} must be passed in order to generate a JWT!");;
        }
 public UserRepository(TokenContext _context, IOptions <TokenOptions> tokenOptions) : base(_context)
 {
     _tokenOptions = tokenOptions.Value;
 }
Example #4
0
 public AuthenticationController(IOptions <TokenOptions> options)
 {
     Options = options.Value;
 }
Example #5
0
 public AuthController(IOptions <TokenOptions> jwtOptions, IUserService userService, IMapper mapper, IAuthorizationService authorizationService) : base(mapper, authorizationService)
 {
     _userService  = userService;
     _tokenOptions = jwtOptions.Value;
 }
Example #6
0
 public JwtHelper(IConfiguration configuration)
 {
     Configuration          = configuration;
     _tokenOptions          = Configuration.GetSection("TokenOptions").Get <TokenOptions>();
     _accessTokenExpiration = DateTime.Now.AddMinutes(_tokenOptions.AccessTokenExpiration);
 }
Example #7
0
        private static TokenValidationParameters BuildTokenValidationParameters(SecurityOptions security, TokenOptions tokens, ClaimOptions claims)
        {
            MaybeSetSecurityKeys(new TokenFabricationRequest
            {
                TokenAudience          = tokens.Audience,
                Encrypt                = tokens.Encrypt,
                EncryptingKey          = security.Encrypting,
                EncryptingKeyString    = tokens.EncryptingKey,
                SigningKey             = security.Signing,
                SigningKeyString       = tokens.SigningKey,
                TokenIssuer            = tokens.Issuer,
                TokenTimeToLiveSeconds = tokens.TimeToLiveSeconds
            });

            var name = claims.UserNameClaim;
            var role = claims.RoleClaim;

            if (tokens.Encrypt)
            {
                return(new TokenValidationParameters
                {
                    TokenDecryptionKeyResolver = (token, securityToken, kid, parameters) => new[] { security.Encrypting.Key },
                    ValidateIssuerSigningKey = false,
                    ValidIssuer = tokens.Issuer,
                    ValidateLifetime = true,
                    ValidateAudience = true,
                    ValidAudience = tokens.Audience,
                    RequireSignedTokens = false,
                    IssuerSigningKey = security.Signing.Key,
                    TokenDecryptionKey = security.Encrypting.Key,
                    ClockSkew = TimeSpan.FromSeconds(tokens.ClockSkewSeconds),
                    RoleClaimType = role,
                    NameClaimType = name
                });
            }

            return(new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                ValidIssuer = tokens.Issuer,
                ValidateLifetime = true,
                ValidateAudience = true,
                ValidAudience = tokens.Audience,
                RequireSignedTokens = true,
                IssuerSigningKey = security.Signing.Key,
                ClockSkew = TimeSpan.FromSeconds(tokens.ClockSkewSeconds),
                RoleClaimType = role,
                NameClaimType = name
            });
        }
 public static DateTime GetExpiration(this TokenOptions options) => DateTime.UtcNow.Add(options.ValidFor);
Example #9
0
 public JwtToken(IOptions <TokenOptions> options, IHttpContextAccessor httpContextAccessor)
 {
     this.options             = options.Value;
     this.httpContextAccessor = httpContextAccessor;
 }
Example #10
0
 public TokenHandler(IOptions <TokenOptions> tokenOptionsSnapshot, SigningConfigurations signingConfigurations, IPasswordHandler passwordHandler)
 {
     _passwordHandler       = passwordHandler;
     _tokenOptions          = tokenOptionsSnapshot.Value;
     _signingConfigurations = signingConfigurations;
 }
Example #11
0
 public TokenHelper(TokenOptions tokenOptions)
 {
     _tokenOptions   = tokenOptions;
     _expirationDate = DateTime.UtcNow.AddMinutes(_tokenOptions.Expiration);
 }
Example #12
0
 public UserService(IOptions <TokenOptions> tokenOptions)
 {
     _tokenOptions = tokenOptions.Value;
 }
 public PersonelRepository(TskSaymanlikDepolariContext context, IOptions <TokenOptions> tokenOptions) : base(context)
 {
     this.tokenOptions = tokenOptions.Value;
 }
 internal TokenDistinctionRule(TokenOptions options) : base(options)
 {
 }
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            //  Test ToneAnalyzer using loaded credentials
            ToneAnalyzer autoToneAnalyzer = new ToneAnalyzer();

            autoToneAnalyzer.VersionDate = _toneAnalyzerVersionDate;
            while (!autoToneAnalyzer.Credentials.HasIamTokenData())
            {
                yield return(null);
            }
            autoToneAnalyzer.GetToneAnalyze(OnAutoGetToneAnalyze, OnFail, _stringToTestTone);
            while (!_autoGetToneAnalyzeTested)
            {
                yield return(null);
            }

            VcapCredentials vcapCredentials = new VcapCredentials();
            fsData          data            = null;

            string result = null;

            string credentialsFilepath = "../sdk-credentials/credentials.json";

            //  Load credentials file if it exists. If it doesn't exist, don't run the tests.
            if (File.Exists(credentialsFilepath))
            {
                result = File.ReadAllText(credentialsFilepath);
            }
            else
            {
                yield break;
            }

            //  Add in a parent object because Unity does not like to deserialize root level collection types.
            result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES");

            //  Convert json to fsResult
            fsResult r = fsJsonParser.Parse(result, out data);

            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Convert fsResult to VcapCredentials
            object obj = vcapCredentials;

            r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Set credentials from imported credntials
            Credential credential = vcapCredentials.GetCredentialByname("tone-analyzer-sdk")[0].Credentials;

            //  Create credential and instantiate service
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = credential.IamApikey,
            };

            //  Create credential and instantiate service
            Credentials credentials = new Credentials(tokenOptions, credential.Url);

            //  Wait for tokendata
            while (!credentials.HasIamTokenData())
            {
                yield return(null);
            }

            _toneAnalyzer             = new ToneAnalyzer(credentials);
            _toneAnalyzer.VersionDate = _toneAnalyzerVersionDate;

            //  Analyze tone
            if (!_toneAnalyzer.GetToneAnalyze(OnGetToneAnalyze, OnFail, _stringToTestTone))
            {
                Log.Debug("ExampleToneAnalyzer.GetToneAnalyze()", "Failed to analyze!");
            }

            while (!_analyzeToneTested)
            {
                yield return(null);
            }

            Log.Debug("ExampleToneAnalyzer.RunTest()", "Tone analyzer examples complete.");

            yield break;
        }
 private static byte[] GetSigningKeyBytes(this TokenOptions options) => Encoding.ASCII.GetBytes(options.SigningKey);
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            VcapCredentials vcapCredentials = new VcapCredentials();
            fsData          data            = null;

            string result = null;
            string credentialsFilepath = "../sdk-credentials/credentials.json";

            //  Load credentials file if it exists. If it doesn't exist, don't run the tests.
            if (File.Exists(credentialsFilepath))
            {
                result = File.ReadAllText(credentialsFilepath);
            }
            else
            {
                yield break;
            }

            //  Add in a parent object because Unity does not like to deserialize root level collection types.
            result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES");

            //  Convert json to fsResult
            fsResult r = fsJsonParser.Parse(result, out data);

            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Convert fsResult to VcapCredentials
            object obj = vcapCredentials;

            r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Set credentials from imported credntials
            Credential credential = vcapCredentials.GetCredentialByname("language-translator-v3-iam-staging")[0].Credentials;

            _url = credential.Url.ToString();

            //  Create credential and instantiate service
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = credential.IamApikey,
                IamUrl    = credential.IamUrl
            };

            Credentials credentials = new Credentials(tokenOptions, credential.Url);

            //  Wait for tokendata
            while (!credentials.HasIamTokenData())
            {
                yield return(null);
            }

            _languageTranslator = new LanguageTranslator(_versionDate, credentials);

            _forcedGlossaryFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/glossary.tmx";

            if (!_languageTranslator.GetTranslation(OnGetTranslation, OnFail, _pharseToTranslate, "en", "es"))
            {
                Log.Debug("TestLanguageTranslator.GetTranslation()", "Failed to translate.");
            }
            while (!_getTranslationTested)
            {
                yield return(null);
            }

            if (!_languageTranslator.GetModels(OnGetModels, OnFail))
            {
                Log.Debug("TestLanguageTranslator.GetModels()", "Failed to get models.");
            }
            while (!_getModelsTested)
            {
                yield return(null);
            }

            if (!_languageTranslator.CreateModel(OnCreateModel, OnFail, _baseModelName, _customModelName, _forcedGlossaryFilePath))
            {
                Log.Debug("TestLanguageTranslator.CreateModel()", "Failed to create model.");
            }
            while (!_createModelTested)
            {
                yield return(null);
            }

            if (!_languageTranslator.GetModel(OnGetModel, OnFail, _customLanguageModelId))
            {
                Log.Debug("TestLanguageTranslator.GetModel()", "Failed to get model.");
            }
            while (!_getModelTested)
            {
                yield return(null);
            }

            if (!_languageTranslator.DeleteModel(OnDeleteModel, OnFail, _customLanguageModelId))
            {
                Log.Debug("TestLanguageTranslator.DeleteModel()", "Failed to delete model.");
            }
            while (!_deleteModelTested)
            {
                yield return(null);
            }

            if (!_languageTranslator.Identify(OnIdentify, OnFail, _pharseToTranslate))
            {
                Log.Debug("TestLanguageTranslator.Identify()", "Failed to identify language.");
            }
            while (!_identifyTested)
            {
                yield return(null);
            }

            if (!_languageTranslator.GetLanguages(OnGetLanguages, OnFail))
            {
                Log.Debug("TestLanguageTranslator.GetLanguages()", "Failed to get languages.");
            }
            while (!_getLanguagesTested)
            {
                yield return(null);
            }

            Log.Debug("TestLanguageTranslator.RunTest()", "Language Translator examples complete.");

            yield break;
        }
Example #18
0
 public JWTHelper(IConfiguration configuration)
 {
     this.Configuration = configuration;
     //Configuration içinden Token Options içinden okuma işlemi gerçekleştirdik
     this._tokenOptions = this.Configuration.GetSection("TokenOptions").Get <TokenOptions>();
 }
 public UserRepository(CoreAPIGITVersionContext _context, IOptions <TokenOptions> _tokenOptions) : base(_context)
 {
     Context      = _context;
     tokenOptions = _tokenOptions.Value;
 }
Example #20
0
        public static void AddAuthentication(this IServiceCollection services,
                                             SecurityOptions security,
                                             SuperUserOptions superUser,
                                             TokenOptions tokens,
                                             CookieOptions cookies,
                                             ClaimOptions claims)
        {
            lock (Sync)
            {
                AuthenticationBuilder authBuilder = null;

                var scheme = tokens.Scheme;

                if (tokens.Enabled || superUser.Enabled || cookies.Enabled)
                {
                    authBuilder = services.AddAuthentication(x =>
                    {
                        x.DefaultScheme             = scheme;
                        x.DefaultAuthenticateScheme = scheme;
                        x.DefaultForbidScheme       = scheme;
                        x.DefaultSignInScheme       = scheme;
                        x.DefaultSignOutScheme      = scheme;
                        x.DefaultChallengeScheme    = scheme;
                    });
                }

                if (tokens.Enabled || superUser.Enabled)
                {
                    var parameters = BuildTokenValidationParameters(security, tokens, claims);

                    authBuilder.AddJwtBearer(scheme, x =>
                    {
                        x.Events = new JwtBearerEvents();
                        x.Events.OnTokenValidated       += OnTokenValidated;
                        x.Events.OnMessageReceived      += OnMessageReceived;
                        x.Events.OnAuthenticationFailed += OnAuthenticationFailed;
                        x.Events.OnChallenge            += OnChallenge;
                        x.SaveToken = true;
                        x.TokenValidationParameters = parameters;
#if DEBUG
                        x.IncludeErrorDetails  = true;
                        x.RequireHttpsMetadata = false;
#else
                        x.IncludeErrorDetails  = false;
                        x.RequireHttpsMetadata = true;
#endif
                    });
                }

                if (cookies.Enabled)
                {
                    authBuilder.AddCookie(cookies.Scheme ?? scheme, cfg =>
                    {
                        cfg.LoginPath          = cookies.SignInPath;
                        cfg.LogoutPath         = cookies.SignOutPath;
                        cfg.AccessDeniedPath   = cookies.ForbidPath;
                        cfg.ReturnUrlParameter = cookies.ReturnOperator;
                        cfg.Events             = new CookieAuthenticationEvents
                        {
                            OnSigningIn = context =>
                            {
                                if (string.IsNullOrWhiteSpace(cookies.Domain))
                                {
                                    context.Options.Cookie.Domain = context.HttpContext.Request.Host.Value;
                                }
                                return(Task.CompletedTask);
                            }
                        };
                        cfg.SlidingExpiration = tokens.AllowRefresh;
                        cfg.ClaimsIssuer      = tokens.Issuer;

                        cfg.Cookie.Name         = cookies.IdentityName;
                        cfg.Cookie.Expiration   = TimeSpan.FromSeconds(tokens.TimeToLiveSeconds);
                        cfg.Cookie.Path         = "/";
                        cfg.Cookie.HttpOnly     = true;
                        cfg.Cookie.IsEssential  = true;
                        cfg.Cookie.SameSite     = SameSiteMode.Strict;
                        cfg.Cookie.MaxAge       = cfg.Cookie.Expiration;
                        cfg.Cookie.SecurePolicy = CookieSecurePolicy.Always;
                    });
                }
            }
        }
Example #21
0
    private IEnumerator createServices()
    {
        Credentials stt_credentials = null;

        //  Create credential and instantiate service
        if (!string.IsNullOrEmpty(speechToTextIamApikey))
        {
            //  Authenticate using iamApikey
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = speechToTextIamApikey,
                IamUrl    = speechToTextIamUrl
            };

            stt_credentials = new Credentials(tokenOptions, speechToTextServiceUrl);

            while (!stt_credentials.HasIamTokenData())
            {
                yield return(null);
            }
        }
        else
        {
            throw new IBMException("Please provide IAM ApiKey for the Speech To Text service.");
        }

        Credentials asst_credentials = null;

        //  Create credential and instantiate service

        if (!string.IsNullOrEmpty(assistantIamApikey))
        {
            //  Authenticate using iamApikey
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = assistantIamApikey
            };

            asst_credentials = new Credentials(tokenOptions, assistantServiceUrl);

            while (!asst_credentials.HasIamTokenData())
            {
                yield return(null);
            }
        }
        else
        {
            throw new IBMException("Please provide IAM ApiKey for the Watson Assistant service.");
        }


        _speechToText = new SpeechToTextService(stt_credentials);
        _assistant    = new AssistantService(assistantVersionDate, asst_credentials);

        _assistant.VersionDate = assistantVersionDate;
        Active = true;

        _assistant.CreateSession(OnCreateSession, assistantId);

        while (!createSessionTested)
        {
            yield return(null);
        }

        StartRecording();
    }
Example #22
0
 public AccountController(IOptions <TokenOptions> jwtOptions, IAuthenticateAppService authenticateAppService)
 {
     _tokenOptions = jwtOptions.Value;
     ThrowIfInvalidOptions(_tokenOptions);
     _authenticateAppService = authenticateAppService;
 }
Example #23
0
    private IEnumerator createServices()
    {
        Credentials stt_credentials = null;

        //  Create credential and instantiate service
        if (!string.IsNullOrEmpty(speechToTextUsername) && !string.IsNullOrEmpty(speechToTextPassword))
        {
            //  Authenticate using username and password
            stt_credentials = new Credentials(speechToTextUsername, speechToTextPassword, speechToTextServiceUrl);
        }
        else if (!string.IsNullOrEmpty(speechToTextIamApikey))
        {
            //  Authenticate using iamApikey
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = speechToTextIamApikey,
                IamUrl    = speechToTextIamUrl
            };

            stt_credentials = new Credentials(tokenOptions, speechToTextServiceUrl);

            while (!stt_credentials.HasIamTokenData())
            {
                yield return(null);
            }
        }
        else
        {
            throw new WatsonException("Please provide either username and password or IAM apikey to authenticate the service.");
        }

        Credentials asst_credentials = null;

        //  Create credential and instantiate service
        if (!string.IsNullOrEmpty(assistantUsername) && !string.IsNullOrEmpty(assitantPassword))
        {
            //  Authenticate using username and password
            asst_credentials = new Credentials(assistantUsername, assitantPassword, assistantServiceUrl);
        }
        else if (!string.IsNullOrEmpty(assistantIamApikey))
        {
            Log.Debug("createServices()", "IAM key", "key {0}", assistantIamApikey);
            //  Authenticate using iamApikey
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = assistantIamApikey,
                IamUrl    = assistantIamUrl
            };

            asst_credentials = new Credentials(tokenOptions, assistantServiceUrl);

            while (!asst_credentials.HasIamTokenData())
            {
                yield return(null);
            }
        }
        else
        {
            throw new WatsonException("Please provide either username and password or IAM apikey to authenticate the service.");
        }

        Credentials lang_credentials = null;

        //  Create credential and instantiate service
        if (!string.IsNullOrEmpty(translatorUsername) && !string.IsNullOrEmpty(translatorPassword))
        {
            //  Authenticate using username and password
            lang_credentials = new Credentials(translatorUsername, translatorPassword, translatorServiceUrl);
        }
        else if (!string.IsNullOrEmpty(translatorIamApikey))
        {
            Log.Debug("createServices()", "IAM key", "key {0}", translatorIamApikey);

            //  Authenticate using iamApikey
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = translatorIamApikey,
                IamUrl    = translatorIamUrl
            };

            lang_credentials = new Credentials(tokenOptions, translatorServiceUrl);

            while (!lang_credentials.HasIamTokenData())
            {
                yield return(null);
            }

            Log.Debug("createServices()", "lang_creds", " {0}", lang_credentials);
        }
        else
        {
            throw new WatsonException("Please provide either username and password or IAM apikey to authenticate the service.");
        }

        _speechToText        = new SpeechToText(stt_credentials);
        _conversation        = new Conversation(asst_credentials);
        _language_translator = new LanguageTranslator(translatorVersionDate, lang_credentials);

        _speechToText.RecognizeModel = "ja-JP_BroadbandModel";
        _conversation.VersionDate    = assistantVersionDate;

        Active = true;

        StartRecording();
    }
Example #24
0
        public static IMvcCoreBuilder AddSuperUserTokenController <TKey>(this IMvcCoreBuilder mvcBuilder, Func <IServiceProvider, DateTimeOffset> timestamps,
                                                                         Action <ClaimOptions> configureClaimsAction        = null,
                                                                         Action <TokenOptions> configureTokensAction        = null,
                                                                         Action <SuperUserOptions> configureSuperUserAction = null)
            where TKey : IEquatable <TKey>
        {
            if (configureClaimsAction != null)
            {
                mvcBuilder.Services.Configure(configureClaimsAction);
            }

            if (configureTokensAction != null)
            {
                mvcBuilder.Services.Configure(configureTokensAction);
            }

            if (configureSuperUserAction != null)
            {
                mvcBuilder.Services.Configure(configureSuperUserAction);
            }

            var claims = new ClaimOptions();

            configureClaimsAction?.Invoke(claims);

            var tokens = new TokenOptions();

            configureTokensAction?.Invoke(tokens);

            var superUser = new SuperUserOptions();

            configureSuperUserAction?.Invoke(superUser);

            var credentials = new
            {
                SigningKeyString    = tokens.SigningKey,
                EncryptingKeyString = tokens.EncryptingKey
            }.QuackLike <ITokenCredentials>();

            AuthenticationExtensions.MaybeSetSecurityKeys(credentials);

            var scheme = superUser.Scheme ?? tokens.Scheme;

            mvcBuilder.Services.AddAuthentication().AddJwtBearer(scheme, o =>
            {
                if (tokens.Encrypt)
                {
                    o.TokenValidationParameters = new TokenValidationParameters
                    {
                        TokenDecryptionKeyResolver = (token, securityToken, kid, parameters) => new[] { credentials.EncryptingKey.Key },
                        ValidateIssuerSigningKey   = false,
                        ValidIssuer         = tokens.Issuer,
                        ValidateLifetime    = true,
                        ValidateAudience    = true,
                        ValidAudience       = tokens.Audience,
                        RequireSignedTokens = false,
                        IssuerSigningKey    = credentials.SigningKey.Key,
                        TokenDecryptionKey  = credentials.EncryptingKey.Key,
                        ClockSkew           = TimeSpan.FromSeconds(tokens.ClockSkewSeconds),
                        RoleClaimType       = claims.RoleClaim,
                        NameClaimType       = claims.UserNameClaim
                    };
                }
                else
                {
                    o.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        ValidIssuer         = tokens.Issuer,
                        ValidateLifetime    = true,
                        ValidateAudience    = true,
                        ValidAudience       = tokens.Audience,
                        RequireSignedTokens = true,
                        IssuerSigningKey    = credentials.SigningKey.Key,
                        ClockSkew           = TimeSpan.FromSeconds(tokens.ClockSkewSeconds),
                        RoleClaimType       = claims.RoleClaim,
                        NameClaimType       = claims.UserNameClaim
                    };
                }
            });

            mvcBuilder.Services.TryAddSingleton <IIdentityClaimNameProvider, DefaultIdentityClaimNameProvider>();
            mvcBuilder.Services.TryAddSingleton <ITokenFabricator <TKey> >(r => new DefaultTokenFabricator <TKey>(() => timestamps(r), r.GetRequiredService <IOptionsSnapshot <TokenOptions> >()));

            mvcBuilder.AddActiveRoute <SuperUserTokenController <TKey>, SuperUserFeature, SuperUserOptions>();
            return(mvcBuilder);
        }
Example #25
0
 public TokenHelper(IOptions <TokenOptions> tokenOptions)
 {
     _tokenOptions = tokenOptions.Value;
 }
Example #26
0
 public UserRepository(ApiWithTokenDBContext context, IOptions <TokenOptions> tokenOptions) : base(context)
 {
     this.tokenOptions = tokenOptions.Value;
 }
        public static IServiceCollection AddJwtAuthenticationWithProtectedCookie(this IServiceCollection services, IConfiguration configuration,
                                                                                 string applicationDiscriminator = null, AuthUrlOptions authUrlOptions = null)
        {
            var tokenOptions = new TokenOptions(
                configuration["Token:Audience"],
                configuration["Token:Issuer"],
                configuration["Token:SigningKey"],
                configuration["Token:ExpiryInMinutes"]);

            var serviceProvider    = services.BuildServiceProvider();
            var hostingEnvironment = serviceProvider.GetService <IHostEnvironment>();

            // The JwtAuthTicketFormat representing the cookie needs an IDataProtector and
            // IDataSerializer to correctly encrypt/decrypt and serialize/deserialize the payload
            // respectively. This requirement is enforced by ISecureDataFormat interface in ASP.NET
            // Core. Read more about ASP.NET Core Data Protection API here:
            // https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/
            // NB: This is only required if you're using JWT with Cookie based authentication, for
            //     cookieless auth (such as with a Web API) the data protection and serialization
            //     dependencies won't be needed. You simply need to set the validation params and add
            //     the token generator dependencies and use the right authentication extension below.

            var applicationName = $"{applicationDiscriminator ?? hostingEnvironment.ApplicationName}";

            services.AddDataProtection(options => options.ApplicationDiscriminator = applicationName)
            .SetApplicationName(applicationName);

            services.AddScoped <IDataSerializer <AuthenticationTicket>, TicketSerializer>();
            services.AddScoped <IJwtTokenAccessor, JwtTokenAccessor>(tokenAccessor => new JwtTokenAccessor(tokenOptions));

            serviceProvider = services.BuildServiceProvider();
            var dataProtector  = serviceProvider.GetDataProtector(new[] { $"{applicationName}-Auth1" });
            var dataSerializer = serviceProvider.GetService <IDataSerializer <AuthenticationTicket> >();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(CookieConstants.TwoFactorRememberMeScheme, options =>
            {
                options.Cookie.Name = CookieConstants.TwoFactorRememberMeScheme;
            })
            .AddCookie(CookieConstants.TwoFactorUserIdScheme, options =>
            {
                options.Cookie.Name    = CookieConstants.TwoFactorUserIdScheme;
                options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Cookie.Name = CookieConstants.ApplicationScheme;
                // cookie expiration should be set the same as the token expiry (the default is 5
                // mins). The token generator doesn't provide auto-refresh of an expired token so the
                // user will be logged out the next time they try to access a secured endpoint. They
                // will simply have to re-login and acquire a new token and by extension a new cookie.
                // Perhaps in the future I can add some kind of hooks in the token generator that can
                // let the referencing application know that the token has expired and the developer
                // can then request a new token without the user having to re-login.
                options.ExpireTimeSpan = TimeSpan.FromMinutes(tokenOptions.TokenExpiryInMinutes);

                // Specify the TicketDataFormat to use to validate/create the ASP.NET authentication
                // ticket. Its important that the same validation parameters are passed to this class
                // so that the token validation works correctly. The framework will call the
                // appropriate methods in JwtAuthTicketFormat based on whether the cookie is being
                // sent out or coming in from a previously authenticated user. Please bear in mind
                // that if the incoming token is invalid (may be it was tampered or spoofed) the
                // Unprotect() method in JwtAuthTicketFormat will simply return null and the
                // authentication will fail.
                options.TicketDataFormat = new JwtAuthTicketFormat(
                    tokenOptions.ToTokenValidationParams(),
                    dataSerializer,
                    dataProtector);

                options.LoginPath          = GetPath(authUrlOptions?.LoginPath, "/Account/Login");
                options.LogoutPath         = GetPath(authUrlOptions?.LogoutPath, "/Account/Logout");
                options.AccessDeniedPath   = GetPath(authUrlOptions?.AccessDeniedPath, "/Account/AccessDenied");
                options.ReturnUrlParameter = authUrlOptions?.ReturnUrlParameter ?? "returnUrl";
            });

            return(services);
        }
Example #28
0
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            VcapCredentials vcapCredentials = new VcapCredentials();
            fsData          data            = null;

            string result = null;
            string credentialsFilepath = "../sdk-credentials/credentials.json";

            //  Load credentials file if it exists. If it doesn't exist, don't run the tests.
            if (File.Exists(credentialsFilepath))
            {
                result = File.ReadAllText(credentialsFilepath);
            }
            else
            {
                yield break;
            }

            //  Add in a parent object because Unity does not like to deserialize root level collection types.
            result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES");

            //  Convert json to fsResult
            fsResult r = fsJsonParser.Parse(result, out data);

            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Convert fsResult to VcapCredentials
            object obj = vcapCredentials;

            r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Set credentials from imported credntials
            Credential credential = vcapCredentials.GetCredentialByname("speech-to-text-sdk")[0].Credentials;
            //  Create credential and instantiate service
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = credential.IamApikey,
            };

            //  Create credential and instantiate service
            Credentials credentials = new Credentials(tokenOptions, credential.Url);

            //  Wait for tokendata
            while (!credentials.HasIamTokenData())
            {
                yield return(null);
            }

            _speechToText             = new SpeechToText(credentials);
            _customCorpusFilePath     = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/theJabberwocky-utf8.txt";
            _customWordsFilePath      = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/test-stt-words.json";
            _acousticResourceMimeType = Utility.GetMimeType(Path.GetExtension(_acousticResourceUrl));

            Runnable.Run(DownloadAcousticResource());
            while (!_isAudioLoaded)
            {
                yield return(null);
            }

            //  Recognize
            Log.Debug("TestSpeechToText.Examples()", "Attempting to recognize");
            List <string> keywords = new List <string>();

            keywords.Add("speech");
            _speechToText.KeywordsThreshold = 0.5f;
            _speechToText.InactivityTimeout = 120;
            _speechToText.StreamMultipart   = false;
            _speechToText.Keywords          = keywords.ToArray();
            _speechToText.Recognize(HandleOnRecognize, OnFail, _acousticResourceData, _acousticResourceMimeType);
            while (!_recognizeTested)
            {
                yield return(null);
            }

            //  Get models
            Log.Debug("TestSpeechToText.Examples()", "Attempting to get models");
            _speechToText.GetModels(HandleGetModels, OnFail);
            while (!_getModelsTested)
            {
                yield return(null);
            }

            //  Get model
            Log.Debug("TestSpeechToText.Examples()", "Attempting to get model {0}", _modelNameToGet);
            _speechToText.GetModel(HandleGetModel, OnFail, _modelNameToGet);
            while (!_getModelTested)
            {
                yield return(null);
            }

            //  Get customizations
            Log.Debug("TestSpeechToText.Examples()", "Attempting to get customizations");
            _speechToText.GetCustomizations(HandleGetCustomizations, OnFail);
            while (!_getCustomizationsTested)
            {
                yield return(null);
            }

            //  Create customization
            Log.Debug("TestSpeechToText.Examples()", "Attempting create customization");
            _speechToText.CreateCustomization(HandleCreateCustomization, OnFail, "unity-test-customization", "en-US_BroadbandModel", "Testing customization unity");
            while (!_createCustomizationsTested)
            {
                yield return(null);
            }

            //  Get customization
            Log.Debug("TestSpeechToText.Examples()", "Attempting to get customization {0}", _createdCustomizationID);
            _speechToText.GetCustomization(HandleGetCustomization, OnFail, _createdCustomizationID);
            while (!_getCustomizationTested)
            {
                yield return(null);
            }

            //  Get custom corpora
            Log.Debug("TestSpeechToText.Examples()", "Attempting to get custom corpora for {0}", _createdCustomizationID);
            _speechToText.GetCustomCorpora(HandleGetCustomCorpora, OnFail, _createdCustomizationID);
            while (!_getCustomCorporaTested)
            {
                yield return(null);
            }

            //  Add custom corpus
            Log.Debug("TestSpeechToText.Examples()", "Attempting to add custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName);
            string corpusData = File.ReadAllText(_customCorpusFilePath);

            _speechToText.AddCustomCorpus(HandleAddCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName, true, corpusData);
            while (!_addCustomCorpusTested)
            {
                yield return(null);
            }

            //  Get custom corpus
            Log.Debug("TestSpeechToText.Examples()", "Attempting to get custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName);
            _speechToText.GetCustomCorpus(HandleGetCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName);
            while (!_getCustomCorpusTested)
            {
                yield return(null);
            }

            //  Wait for customization
            Runnable.Run(CheckCustomizationStatus(_createdCustomizationID));
            while (!_isCustomizationReady)
            {
                yield return(null);
            }

            //  Get custom words
            Log.Debug("TestSpeechToText.Examples()", "Attempting to get custom words.");
            _speechToText.GetCustomWords(HandleGetCustomWords, OnFail, _createdCustomizationID);
            while (!_getCustomWordsTested)
            {
                yield return(null);
            }

            //  Add custom words from path
            Log.Debug("TestSpeechToText.Examples()", "Attempting to add custom words in customization {0} using Words json path {1}", _createdCustomizationID, _customWordsFilePath);
            string customWords = File.ReadAllText(_customWordsFilePath);

            _speechToText.AddCustomWords(HandleAddCustomWordsFromPath, OnFail, _createdCustomizationID, customWords);
            while (!_addCustomWordsFromPathTested)
            {
                yield return(null);
            }

            //  Wait for customization
            _isCustomizationReady = false;
            Runnable.Run(CheckCustomizationStatus(_createdCustomizationID));
            while (!_isCustomizationReady)
            {
                yield return(null);
            }

            //  Add custom words from object
            Words       words    = new Words();
            Word        w0       = new Word();
            List <Word> wordList = new List <Word>();

            w0.word           = "mikey";
            w0.sounds_like    = new string[1];
            w0.sounds_like[0] = "my key";
            w0.display_as     = "Mikey";
            wordList.Add(w0);
            Word w1 = new Word();

            w1.word           = "charlie";
            w1.sounds_like    = new string[1];
            w1.sounds_like[0] = "char lee";
            w1.display_as     = "Charlie";
            wordList.Add(w1);
            Word w2 = new Word();

            w2.word           = "bijou";
            w2.sounds_like    = new string[1];
            w2.sounds_like[0] = "be joo";
            w2.display_as     = "Bijou";
            wordList.Add(w2);
            words.words = wordList.ToArray();

            Log.Debug("TestSpeechToText.Examples()", "Attempting to add custom words in customization {0} using Words object", _createdCustomizationID);
            _speechToText.AddCustomWords(HandleAddCustomWordsFromObject, OnFail, _createdCustomizationID, words);
            while (!_addCustomWordsFromObjectTested)
            {
                yield return(null);
            }

            //  Wait for customization
            _isCustomizationReady = false;
            Runnable.Run(CheckCustomizationStatus(_createdCustomizationID));
            while (!_isCustomizationReady)
            {
                yield return(null);
            }

            //  Get custom word
            Log.Debug("TestSpeechToText.Examples()", "Attempting to get custom word {1} in customization {0}", _createdCustomizationID, words.words[0].word);
            _speechToText.GetCustomWord(HandleGetCustomWord, OnFail, _createdCustomizationID, words.words[0].word);
            while (!_getCustomWordTested)
            {
                yield return(null);
            }

            //  Train customization
            Log.Debug("TestSpeechToText.Examples()", "Attempting to train customization {0}", _createdCustomizationID);
            _speechToText.TrainCustomization(HandleTrainCustomization, OnFail, _createdCustomizationID);
            while (!_trainCustomizationTested)
            {
                yield return(null);
            }

            //  Wait for customization
            _isCustomizationReady = false;
            Runnable.Run(CheckCustomizationStatus(_createdCustomizationID));
            while (!_isCustomizationReady)
            {
                yield return(null);
            }

            //  Upgrade customization - not currently implemented in service
            //Log.Debug("TestSpeechToText.Examples()", "Attempting to upgrade customization {0}", _createdCustomizationID);
            //_speechToText.UpgradeCustomization(HandleUpgradeCustomization, _createdCustomizationID);
            //while (!_upgradeCustomizationTested)
            //    yield return null;

            //  Delete custom word
            Log.Debug("TestSpeechToText.Examples()", "Attempting to delete custom word {1} in customization {0}", _createdCustomizationID, words.words[2].word);
            _speechToText.DeleteCustomWord(HandleDeleteCustomWord, OnFail, _createdCustomizationID, words.words[2].word);
            while (!_deleteCustomWordTested)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("TestSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds));
            Runnable.Run(Delay(_delayTimeInSeconds));
            while (!_readyToContinue)
            {
                yield return(null);
            }

            _readyToContinue = false;
            //  Delete custom corpus
            Log.Debug("TestSpeechToText.Examples()", "Attempting to delete custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName);
            _speechToText.DeleteCustomCorpus(HandleDeleteCustomCorpus, OnFail, _createdCustomizationID, _createdCorpusName);
            while (!_deleteCustomCorpusTested)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("TestSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds));
            Runnable.Run(Delay(_delayTimeInSeconds));
            while (!_readyToContinue)
            {
                yield return(null);
            }

            _readyToContinue = false;
            //  Reset customization
            Log.Debug("TestSpeechToText.Examples()", "Attempting to reset customization {0}", _createdCustomizationID);
            _speechToText.ResetCustomization(HandleResetCustomization, OnFail, _createdCustomizationID);
            while (!_resetCustomizationTested)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("TestSpeechToText.Examples()", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds));
            Runnable.Run(Delay(_delayTimeInSeconds));
            while (!_readyToContinue)
            {
                yield return(null);
            }

            _readyToContinue = false;
            //  Delete customization
            Log.Debug("TestSpeechToText.Examples()", "Attempting to delete customization {0}", _createdCustomizationID);
            _speechToText.DeleteCustomization(HandleDeleteCustomization, OnFail, _createdCustomizationID);
            while (!_deleteCustomizationsTested)
            {
                yield return(null);
            }

            //  List acoustic customizations
            Log.Debug("TestSpeechToText.Examples()", "Attempting to get acoustic customizations");
            _speechToText.GetCustomAcousticModels(HandleGetCustomAcousticModels, OnFail);
            while (!_getAcousticCustomizationsTested)
            {
                yield return(null);
            }

            //  Create acoustic customization
            Log.Debug("TestSpeechToText.Examples()", "Attempting to create acoustic customization");
            _speechToText.CreateAcousticCustomization(HandleCreateAcousticCustomization, OnFail, _createdAcousticModelName);
            while (!_createAcousticCustomizationsTested)
            {
                yield return(null);
            }

            //  Get acoustic customization
            Log.Debug("TestSpeechToText.Examples()", "Attempting to get acoustic customization {0}", _createdAcousticModelId);
            _speechToText.GetCustomAcousticModel(HandleGetCustomAcousticModel, OnFail, _createdAcousticModelId);
            while (!_getAcousticCustomizationTested)
            {
                yield return(null);
            }

            while (!_isAudioLoaded)
            {
                yield return(null);
            }

            //  Create acoustic resource
            Log.Debug("TestSpeechToText.Examples()", "Attempting to create audio resource {1} on {0}", _createdAcousticModelId, _acousticResourceName);
            string mimeType = Utility.GetMimeType(Path.GetExtension(_acousticResourceUrl));

            _speechToText.AddAcousticResource(HandleAddAcousticResource, OnFail, _createdAcousticModelId, _acousticResourceName, mimeType, mimeType, true, _acousticResourceData);
            while (!_addAcousticResourcesTested)
            {
                yield return(null);
            }

            //  Wait for customization
            _isAcousticCustomizationReady = false;
            Runnable.Run(CheckAcousticCustomizationStatus(_createdAcousticModelId));
            while (!_isAcousticCustomizationReady)
            {
                yield return(null);
            }

            //  List acoustic resources
            Log.Debug("TestSpeechToText.Examples()", "Attempting to get audio resources {0}", _createdAcousticModelId);
            _speechToText.GetCustomAcousticResources(HandleGetCustomAcousticResources, OnFail, _createdAcousticModelId);
            while (!_getAcousticResourcesTested)
            {
                yield return(null);
            }

            //  Train acoustic customization
            Log.Debug("TestSpeechToText.Examples()", "Attempting to train acoustic customization {0}", _createdAcousticModelId);
            _speechToText.TrainAcousticCustomization(HandleTrainAcousticCustomization, OnFail, _createdAcousticModelId, null, true);
            while (!_trainAcousticCustomizationsTested)
            {
                yield return(null);
            }

            //  Get acoustic resource
            Log.Debug("TestSpeechToText.Examples()", "Attempting to get audio resource {1} from {0}", _createdAcousticModelId, _acousticResourceName);
            _speechToText.GetCustomAcousticResource(HandleGetCustomAcousticResource, OnFail, _createdAcousticModelId, _acousticResourceName);
            while (!_getAcousticResourceTested)
            {
                yield return(null);
            }

            //  Wait for customization
            _isAcousticCustomizationReady = false;
            Runnable.Run(CheckAcousticCustomizationStatus(_createdAcousticModelId));
            while (!_isAcousticCustomizationReady)
            {
                yield return(null);
            }

            //  Delete acoustic resource
            DeleteAcousticResource();
            while (!_deleteAcousticResource)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("TestSpeechToText.Examples()", string.Format("Delaying delete acoustic resource for {0} sec", _delayTimeInSeconds));
            Runnable.Run(Delay(_delayTimeInSeconds));
            while (!_readyToContinue)
            {
                yield return(null);
            }

            //  Reset acoustic customization
            Log.Debug("TestSpeechToText.Examples()", "Attempting to reset acoustic customization {0}", _createdAcousticModelId);
            _speechToText.ResetAcousticCustomization(HandleResetAcousticCustomization, OnFail, _createdAcousticModelId);
            while (!_resetAcousticCustomizationsTested)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("TestSpeechToText.Examples()", string.Format("Delaying delete acoustic customization for {0} sec", _delayTimeInSeconds));
            Runnable.Run(Delay(_delayTimeInSeconds));
            while (!_readyToContinue)
            {
                yield return(null);
            }

            //  Delete acoustic customization
            DeleteAcousticCustomization();
            while (!_deleteAcousticCustomizationsTested)
            {
                yield return(null);
            }

            //  Delay
            Log.Debug("TestSpeechToText.Examples()", string.Format("Delaying complete for {0} sec", _delayTimeInSeconds));
            Runnable.Run(Delay(_delayTimeInSeconds));
            while (!_readyToContinue)
            {
                yield return(null);
            }

            Log.Debug("TestSpeechToText.RunTest()", "Speech to Text examples complete.");

            yield break;
        }
 public static SigningCredentials GetSigningCredentials(this TokenOptions options) => new SigningCredentials(options.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256);
 public static SymmetricSecurityKey GetSymmetricSecurityKey(this TokenOptions options) => new SymmetricSecurityKey(options.GetSigningKeyBytes());
Example #31
0
        public override IEnumerator RunTest()
        {
            LogSystem.InstallDefaultReactors();

            VcapCredentials vcapCredentials = new VcapCredentials();
            fsData          data            = null;

            string result = null;
            string credentialsFilepath = "../sdk-credentials/credentials.json";

            //  Load credentials file if it exists. If it doesn't exist, don't run the tests.
            if (File.Exists(credentialsFilepath))
            {
                result = File.ReadAllText(credentialsFilepath);
            }
            else
            {
                yield break;
            }

            //  Add in a parent object because Unity does not like to deserialize root level collection types.
            result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES");

            //  Convert json to fsResult
            fsResult r = fsJsonParser.Parse(result, out data);

            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Convert fsResult to VcapCredentials
            object obj = vcapCredentials;

            r = _serializer.TryDeserialize(data, obj.GetType(), ref obj);
            if (!r.Succeeded)
            {
                throw new WatsonException(r.FormattedMessages);
            }

            //  Set credentials from imported credntials
            Credential credential = vcapCredentials.GetCredentialByname("assistant-sdk-iam")[0].Credentials;
            //  Create credential and instantiate service
            TokenOptions tokenOptions = new TokenOptions()
            {
                IamApiKey = credential.IamApikey,
                IamUrl    = "https://iam.stage1.bluemix.net/identity/token"
            };

            Credentials credentials = new Credentials(tokenOptions, credential.Url);

            _workspaceId = credential.WorkspaceId.ToString();

            //  Wait for tokendata
            while (!credentials.HasIamTokenData())
            {
                yield return(null);
            }

            _service             = new Assistant(credentials);
            _service.VersionDate = _assistantVersionDate;

            //  List Workspaces
            _service.ListWorkspaces(OnListWorkspaces, OnFail);
            while (!_listWorkspacesTested)
            {
                yield return(null);
            }
            //  Create Workspace
            CreateWorkspace workspace = new CreateWorkspace()
            {
                Name           = _createdWorkspaceName,
                Description    = _createdWorkspaceDescription,
                Language       = _createdWorkspaceLanguage,
                LearningOptOut = true
            };

            _service.CreateWorkspace(OnCreateWorkspace, OnFail, workspace);
            while (!_createWorkspaceTested)
            {
                yield return(null);
            }
            //  Get Workspace
            _service.GetWorkspace(OnGetWorkspace, OnFail, _createdWorkspaceId);
            while (!_getWorkspaceTested)
            {
                yield return(null);
            }
            //  Update Workspace
            UpdateWorkspace updateWorkspace = new UpdateWorkspace()
            {
                Name        = _createdWorkspaceName + "-updated",
                Description = _createdWorkspaceDescription + "-updated",
                Language    = _createdWorkspaceLanguage
            };

            _service.UpdateWorkspace(OnUpdateWorkspace, OnFail, _createdWorkspaceId, updateWorkspace);
            while (!_updateWorkspaceTested)
            {
                yield return(null);
            }

            //  Message with customerID
            //  Create customData object
            Dictionary <string, object> customData = new Dictionary <string, object>();
            //  Create a dictionary of custom headers
            Dictionary <string, string> customHeaders = new Dictionary <string, string>();

            //  Add to the header dictionary
            customHeaders.Add("X-Watson-Metadata", "customer_id=" + _unitySdkTestCustomerID);
            //  Add the header dictionary to the custom data object
            customData.Add(Constants.String.CUSTOM_REQUEST_HEADERS, customHeaders);
            Dictionary <string, object> input = new Dictionary <string, object>();

            input.Add("text", _inputString);
            MessageRequest messageRequest = new MessageRequest()
            {
                Input = input
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest, null, customData);
            while (!_messageTested)
            {
                yield return(null);
            }
            _messageTested = false;

            input["text"] = _conversationString0;
            MessageRequest messageRequest0 = new MessageRequest()
            {
                Input   = input,
                Context = _context
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest0);
            while (!_messageTested)
            {
                yield return(null);
            }
            _messageTested = false;

            input["text"] = _conversationString1;
            MessageRequest messageRequest1 = new MessageRequest()
            {
                Input   = input,
                Context = _context
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest1);
            while (!_messageTested)
            {
                yield return(null);
            }
            _messageTested = false;

            input["text"] = _conversationString2;
            MessageRequest messageRequest2 = new MessageRequest()
            {
                Input   = input,
                Context = _context
            };

            _service.Message(OnMessage, OnFail, _workspaceId, messageRequest2);
            while (!_messageTested)
            {
                yield return(null);
            }

            //  List Intents
            _service.ListIntents(OnListIntents, OnFail, _createdWorkspaceId);
            while (!_listIntentsTested)
            {
                yield return(null);
            }
            //  Create Intent
            CreateIntent createIntent = new CreateIntent()
            {
                Intent      = _createdIntent,
                Description = _createdIntentDescription
            };

            _service.CreateIntent(OnCreateIntent, OnFail, _createdWorkspaceId, createIntent);
            while (!_createIntentTested)
            {
                yield return(null);
            }
            //  Get Intent
            _service.GetIntent(OnGetIntent, OnFail, _createdWorkspaceId, _createdIntent);
            while (!_getIntentTested)
            {
                yield return(null);
            }
            //  Update Intents
            string       updatedIntent            = _createdIntent + "-updated";
            string       updatedIntentDescription = _createdIntentDescription + "-updated";
            UpdateIntent updateIntent             = new UpdateIntent()
            {
                Intent      = updatedIntent,
                Description = updatedIntentDescription
            };

            _service.UpdateIntent(OnUpdateIntent, OnFail, _createdWorkspaceId, _createdIntent, updateIntent);
            while (!_updateIntentTested)
            {
                yield return(null);
            }

            //  List Examples
            _service.ListExamples(OnListExamples, OnFail, _createdWorkspaceId, updatedIntent);
            while (!_listExamplesTested)
            {
                yield return(null);
            }
            //  Create Examples
            CreateExample createExample = new CreateExample()
            {
                Text = _createdExample
            };

            _service.CreateExample(OnCreateExample, OnFail, _createdWorkspaceId, updatedIntent, createExample);
            while (!_createExampleTested)
            {
                yield return(null);
            }
            //  Get Example
            _service.GetExample(OnGetExample, OnFail, _createdWorkspaceId, updatedIntent, _createdExample);
            while (!_getExampleTested)
            {
                yield return(null);
            }
            //  Update Examples
            string        updatedExample = _createdExample + "-updated";
            UpdateExample updateExample  = new UpdateExample()
            {
                Text = updatedExample
            };

            _service.UpdateExample(OnUpdateExample, OnFail, _createdWorkspaceId, updatedIntent, _createdExample, updateExample);
            while (!_updateExampleTested)
            {
                yield return(null);
            }

            //  List Entities
            _service.ListEntities(OnListEntities, OnFail, _createdWorkspaceId);
            while (!_listEntitiesTested)
            {
                yield return(null);
            }
            //  Create Entities
            CreateEntity entity = new CreateEntity()
            {
                Entity      = _createdEntity,
                Description = _createdEntityDescription
            };

            _service.CreateEntity(OnCreateEntity, OnFail, _createdWorkspaceId, entity);
            while (!_createEntityTested)
            {
                yield return(null);
            }
            //  Get Entity
            _service.GetEntity(OnGetEntity, OnFail, _createdWorkspaceId, _createdEntity);
            while (!_getEntityTested)
            {
                yield return(null);
            }
            //  Update Entities
            string       updatedEntity            = _createdEntity + "-updated";
            string       updatedEntityDescription = _createdEntityDescription + "-updated";
            UpdateEntity updateEntity             = new UpdateEntity()
            {
                Entity      = updatedEntity,
                Description = updatedEntityDescription
            };

            _service.UpdateEntity(OnUpdateEntity, OnFail, _createdWorkspaceId, _createdEntity, updateEntity);
            while (!_updateEntityTested)
            {
                yield return(null);
            }

            //  List Values
            _service.ListValues(OnListValues, OnFail, _createdWorkspaceId, updatedEntity);
            while (!_listValuesTested)
            {
                yield return(null);
            }
            //  Create Values
            CreateValue value = new CreateValue()
            {
                Value = _createdValue
            };

            _service.CreateValue(OnCreateValue, OnFail, _createdWorkspaceId, updatedEntity, value);
            while (!_createValueTested)
            {
                yield return(null);
            }
            //  Get Value
            _service.GetValue(OnGetValue, OnFail, _createdWorkspaceId, updatedEntity, _createdValue);
            while (!_getValueTested)
            {
                yield return(null);
            }
            //  Update Values
            string      updatedValue = _createdValue + "-updated";
            UpdateValue updateValue  = new UpdateValue()
            {
                Value = updatedValue
            };

            _service.UpdateValue(OnUpdateValue, OnFail, _createdWorkspaceId, updatedEntity, _createdValue, updateValue);
            while (!_updateValueTested)
            {
                yield return(null);
            }

            //  List Synonyms
            _service.ListSynonyms(OnListSynonyms, OnFail, _createdWorkspaceId, updatedEntity, updatedValue);
            while (!_listSynonymsTested)
            {
                yield return(null);
            }
            //  Create Synonyms
            CreateSynonym synonym = new CreateSynonym()
            {
                Synonym = _createdSynonym
            };

            _service.CreateSynonym(OnCreateSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, synonym);
            while (!_createSynonymTested)
            {
                yield return(null);
            }
            //  Get Synonym
            _service.GetSynonym(OnGetSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, _createdSynonym);
            while (!_getSynonymTested)
            {
                yield return(null);
            }
            //  Update Synonyms
            string        updatedSynonym = _createdSynonym + "-updated";
            UpdateSynonym updateSynonym  = new UpdateSynonym()
            {
                Synonym = updatedSynonym
            };

            _service.UpdateSynonym(OnUpdateSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, _createdSynonym, updateSynonym);
            while (!_updateSynonymTested)
            {
                yield return(null);
            }

            //  List Dialog Nodes
            _service.ListDialogNodes(OnListDialogNodes, OnFail, _createdWorkspaceId);
            while (!_listDialogNodesTested)
            {
                yield return(null);
            }
            //  Create Dialog Nodes
            CreateDialogNode createDialogNode = new CreateDialogNode()
            {
                DialogNode  = _dialogNodeName,
                Description = _dialogNodeDesc
            };

            _service.CreateDialogNode(OnCreateDialogNode, OnFail, _createdWorkspaceId, createDialogNode);
            while (!_createDialogNodeTested)
            {
                yield return(null);
            }
            //  Get Dialog Node
            _service.GetDialogNode(OnGetDialogNode, OnFail, _createdWorkspaceId, _dialogNodeName);
            while (!_getDialogNodeTested)
            {
                yield return(null);
            }
            //  Update Dialog Nodes
            string           updatedDialogNodeName        = _dialogNodeName + "_updated";
            string           updatedDialogNodeDescription = _dialogNodeDesc + "_updated";
            UpdateDialogNode updateDialogNode             = new UpdateDialogNode()
            {
                DialogNode  = updatedDialogNodeName,
                Description = updatedDialogNodeDescription
            };

            _service.UpdateDialogNode(OnUpdateDialogNode, OnFail, _createdWorkspaceId, _dialogNodeName, updateDialogNode);
            while (!_updateDialogNodeTested)
            {
                yield return(null);
            }

            //  List Logs In Workspace
            _service.ListLogs(OnListLogs, OnFail, _createdWorkspaceId);
            while (!_listLogsInWorkspaceTested)
            {
                yield return(null);
            }
            //  List All Logs
            var filter = "(language::en,request.context.metadata.deployment::deployment_1)";

            _service.ListAllLogs(OnListAllLogs, OnFail, filter);
            while (!_listAllLogsTested)
            {
                yield return(null);
            }

            //  List Counterexamples
            _service.ListCounterexamples(OnListCounterexamples, OnFail, _createdWorkspaceId);
            while (!_listCounterexamplesTested)
            {
                yield return(null);
            }
            //  Create Counterexamples
            CreateCounterexample example = new CreateCounterexample()
            {
                Text = _createdCounterExampleText
            };

            _service.CreateCounterexample(OnCreateCounterexample, OnFail, _createdWorkspaceId, example);
            while (!_createCounterexampleTested)
            {
                yield return(null);
            }
            //  Get Counterexample
            _service.GetCounterexample(OnGetCounterexample, OnFail, _createdWorkspaceId, _createdCounterExampleText);
            while (!_getCounterexampleTested)
            {
                yield return(null);
            }
            //  Update Counterexamples
            string updatedCounterExampleText          = _createdCounterExampleText + "-updated";
            UpdateCounterexample updateCounterExample = new UpdateCounterexample()
            {
                Text = updatedCounterExampleText
            };

            _service.UpdateCounterexample(OnUpdateCounterexample, OnFail, _createdWorkspaceId, _createdCounterExampleText, updateCounterExample);
            while (!_updateCounterexampleTested)
            {
                yield return(null);
            }

            //  Delete Counterexample
            _service.DeleteCounterexample(OnDeleteCounterexample, OnFail, _createdWorkspaceId, updatedCounterExampleText);
            while (!_deleteCounterexampleTested)
            {
                yield return(null);
            }
            //  Delete Dialog Node
            _service.DeleteDialogNode(OnDeleteDialogNode, OnFail, _createdWorkspaceId, updatedDialogNodeName);
            while (!_deleteDialogNodeTested)
            {
                yield return(null);
            }
            //  Delete Synonym
            _service.DeleteSynonym(OnDeleteSynonym, OnFail, _createdWorkspaceId, updatedEntity, updatedValue, updatedSynonym);
            while (!_deleteSynonymTested)
            {
                yield return(null);
            }
            //  Delete Value
            _service.DeleteValue(OnDeleteValue, OnFail, _createdWorkspaceId, updatedEntity, updatedValue);
            while (!_deleteValueTested)
            {
                yield return(null);
            }
            //  Delete Entity
            _service.DeleteEntity(OnDeleteEntity, OnFail, _createdWorkspaceId, updatedEntity);
            while (!_deleteEntityTested)
            {
                yield return(null);
            }
            //  Delete Example
            _service.DeleteExample(OnDeleteExample, OnFail, _createdWorkspaceId, updatedIntent, updatedExample);
            while (!_deleteExampleTested)
            {
                yield return(null);
            }
            //  Delete Intent
            _service.DeleteIntent(OnDeleteIntent, OnFail, _createdWorkspaceId, updatedIntent);
            while (!_deleteIntentTested)
            {
                yield return(null);
            }
            //  Delete Workspace
            _service.DeleteWorkspace(OnDeleteWorkspace, OnFail, _createdWorkspaceId);
            while (!_deleteWorkspaceTested)
            {
                yield return(null);
            }
            //  Delete User Data
            _service.DeleteUserData(OnDeleteUserData, OnFail, _unitySdkTestCustomerID);
            while (!_deleteUserDataTested)
            {
                yield return(null);
            }

            Log.Debug("TestAssistant.RunTest()", "Assistant examples complete.");

            yield break;
        }