Ejemplo n.º 1
0
        public static AuthenticationConfiguration CreateBasicAuthConfig(IConfigurationRepository configuration, IUserRepository userRepository)
        {
            var authConfig = new AuthenticationConfiguration
            {
                InheritHostClientIdentity = false,
                RequireSsl = !configuration.Global.DisableSSL,
                ClaimsAuthenticationManager = new ClaimsTransformer()
            };

            authConfig.AddBasicAuthentication((userName, password) => userRepository.ValidateUser(userName, password));
            return authConfig;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Instantiate right away.
        /// </summary>
        private Configuration()
        {
            var builder = new ConfigurationBuilder()
            .AddJsonFile("config.json")
            .AddJsonFile("config.local.json", optional: true)
            .AddEnvironmentVariables();
            configuration = builder.Build();

            ConnectionStrings = new ConnectionStringConfiguration(configuration.GetSection("ConnectionStrings"));
            Label = new LabelConfiguration(configuration.GetSection("Label"));
            Authentication = new AuthenticationConfiguration(configuration.GetSection("Authentication"));
        }
Ejemplo n.º 3
0
        public static AuthenticationConfiguration CreateClientAuthConfig(IConfigurationRepository configuration)
        {
            var authConfig = new AuthenticationConfiguration
            {
                InheritHostClientIdentity = false,
                RequireSsl = !configuration.Global.DisableSSL,
            };

            // accept arbitrary credentials on basic auth header,
            // validation will be done in the protocol endpoint
            authConfig.AddBasicAuthentication((id, secret) => true, retainPassword: true);
            return authConfig;
        }
        public static AuthenticationConfiguration CreateClientAuthConfig()
        {
            var authConfig = new AuthenticationConfiguration
            {
                InheritHostClientIdentity = false,
                DefaultAuthenticationScheme = "Basic",
            };

            // accept arbitrary credentials on basic auth header,
            // validation will be done in the protocol endpoint
            authConfig.AddBasicAuthentication((id, secret) => true, retainPassword: true);

            return authConfig;
        }
Ejemplo n.º 5
0
        public static AuthenticationConfiguration CreateUserInfoAuthConfig(IConfigurationRepository configuration)
        {
            var userInfoAuth = new AuthenticationConfiguration
            {
                RequireSsl = !configuration.Global.DisableSSL,
                InheritHostClientIdentity = false
            };

            userInfoAuth.AddJsonWebToken(
                issuer: configuration.Global.IssuerUri,
                audience: configuration.Global.IssuerUri + "/userinfo",
                signingCertificate: configuration.Keys.SigningCertificate);

            return userInfoAuth;
        }
Ejemplo n.º 6
0
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            Forms.Init(this, bundle);

            CustomTabsConfiguration.CustomTabsClosingMessage = null;
            AuthenticationConfiguration.Init(this, bundle);
            CrossCurrentActivity.Current.Init(this, bundle);

            FormsMaps.Init(this, bundle);

            LoadApplication(new App(new PlatformInitializer()));
        }
        public static AuthenticationConfiguration Create(AuthenticationService authService)
        {
            var authentication = new AuthenticationConfiguration
            {
                ClaimsAuthenticationManager = new RestClaimsAuthenticationManager(authService),
                RequireSsl         = false,
                EnableSessionToken = true
            };

            #region Basic Authentication

            authentication.AddBasicAuthentication((username, password) => ValidateUser(username, password, authService));

            #endregion

            return(authentication);
        }
Ejemplo n.º 8
0
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
#if DEBUG
            Calabash.Start();
#endif

            Forms.Init();

            AuthenticationConfiguration.Init();
            UIApplication.SharedApplication.StatusBarHidden = false;

            FormsMaps.Init();

            LoadApplication(new App(new PlatformInitializer()));

            return(base.FinishedLaunching(app, options));
        }
Ejemplo n.º 9
0
        public static async Task <JwtToken> RefreshTokenAsync(HttpContext context, AuthenticationConfiguration authConfig)
        {
            if (authConfig.AuthType == AuthType.Jwt)
            {
                var jwtToken = await context.ReadModelAsync <JwtToken>();

                if (jwtToken is JwtToken)
                {
                    var claims      = JWTValidate(jwtToken.Token, authConfig);
                    var credentials = GetCredentials(authConfig, claims);

                    return(CreateJwtToken(authConfig, credentials));
                }
            }

            throw new CredentialsException("Refresh token failed");
        }
Ejemplo n.º 10
0
        private static void ConfigureAuth(HttpConfiguration config)
        {
            var authConfig = new AuthenticationConfiguration
            {
                DefaultAuthenticationScheme       = "Basic",
                EnableSessionToken                = true,
                SendWwwAuthenticateResponseHeader = true,
                RequireSsl = false
            };

            authConfig.AddBasicAuthentication((username, password) =>
            {
                return(username == "admin" && password == "password");
            });

            config.MessageHandlers.Add(new AuthenticationHandler(authConfig));
        }
Ejemplo n.º 11
0
        public void Arrange()
        {
            _distributionRepositoryMock = new Mock <IDistributionRepository>();
            _distributionRepositoryMock.Setup(r =>
                                              r.GetAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((string id, string subscriptionId, CancellationToken cancellationToken) =>
                          new Distribution
            {
                Id             = id,
                SubscriptionId = subscriptionId,
                Status         = DistributionStatus.Pending,
            });

            _eventRepositoryMock = new Mock <IEventRepository>();
            _eventRepositoryMock.Setup(r => r.GetAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new Event());

            _subscriptionRepositoryMock = new Mock <ISubscriptionRepository>();
            _subscriptionRepositoryMock.Setup(r => r.GetSubscriptionToEventAsync(It.IsAny <string>(), It.IsAny <string>(),
                                                                                 It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new Subscription());

            _restClientMock = new Mock <IRestClient>();
            _restClientMock.Setup(c => c.ExecuteTaskAsync(It.IsAny <IRestRequest>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new RestResponse
            {
                StatusCode     = HttpStatusCode.OK,
                ResponseStatus = ResponseStatus.Completed,
            });
            _restClientMock.Setup(c => c.DefaultParameters)
            .Returns(new List <Parameter>());

            _authenticationConfiguration = new AuthenticationConfiguration();

            _loggerMock = new Mock <ILoggerWrapper>();

            _manager = new SendManager(
                _distributionRepositoryMock.Object,
                _eventRepositoryMock.Object,
                _subscriptionRepositoryMock.Object,
                _restClientMock.Object,
                _authenticationConfiguration,
                _loggerMock.Object);

            _cancellationToken = new CancellationToken();
        }
Ejemplo n.º 12
0
        /// <summary>
        /// SetApplication will change the application context of principal object
        /// so that principal object represents the user membership information of
        /// a given application
        /// </summary>
        /// <param name="application">name of the application for which SAFPrincipal will switch the its membership information.</param>
        public void SetApplication(string application)
        {
            SAF.Configuration.ConfigurationManager cm = (SAF.Configuration.ConfigurationManager)System.Configuration.ConfigurationManager.GetSection("Framework");
            AuthenticationConfiguration            ac = cm.AuthenticationConfig;
            //retrieve the type informatioin for the principal object of a given applicaiton
            string      typeName    = ac.GetPrincipalTypeForApplication(application);
            string      appUserName = cm.AuthenticationConfig.GetIdentityForApplicaiton(safUser, application);
            SAFIdentity safIdentity = new SAFIdentity(appUserName, application);
            Type        type        = Type.GetType(typeName);

            object[] parameters = new object[1] {
                safIdentity
            };
            //set the new object to the internal principal object.
            currentApplicationPrincipal = (IPrincipal)Activator.CreateInstance(type, parameters);
            identity = (IIdentity)safIdentity;
        }
        public static void Configure(HttpConfiguration config)
        {
            var authNConfig = new AuthenticationConfiguration();

            authNConfig.AddJsonWebToken(
                "http://identityserver.v2.thinktecture.com/trust/cw",
                "http://tt.com/mobile/todos",
                ConfigurationManager.AppSettings["oauthSigningKey"],
                AuthenticationOptions.ForAuthorizationHeader("Bearer"));

            authNConfig.ClaimsAuthenticationManager =
                FederatedAuthentication.FederationConfiguration
                .IdentityConfiguration.ClaimsAuthenticationManager;

            config.MessageHandlers.Add(new AuthenticationHandler(authNConfig));
            config.Filters.Add(new ClaimsAuthorizeAttribute());
        }
Ejemplo n.º 14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            AuthenticationConfiguration.AddConfigure(app);
            DevelopmentConfiguration.AddConfigure(app, env);

            app.UseStaticFiles();
            app.UseFileServer();
            CorsConfiguration.AddConfigure(app);
            ExceptionConfiguration.AddConfigure(app);

            var serviceProvider     = app.ApplicationServices;
            var httpContextAccessor = serviceProvider.GetRequiredService <IHttpContextAccessor>();

            AuthenticationContextService.AddConfigure(httpContextAccessor);
            RouteConfiguration.AddConfigure(app);
            RouteAnalyzerExtension.AddConfigure(app);
        }
Ejemplo n.º 15
0
        /// <summary>
        ///     Generate a verified output of a function given the correct canary, to be used as a key confirmation.
        /// </summary>
        /// <param name="configuration">Configuration of the verification function.</param>
        /// <param name="canary">Confirmation canary to generate a confirmation output verification for.</param>
        /// <returns>Output of the verification function, given the correct canary.</returns>
        /// <exception cref="ArgumentException">Key is null or zero-length.</exception>
        /// <seealso cref="SymmetricKey"/>
        /// <seealso cref="ECKeypair"/>
        /// <seealso cref="IPossessConfirmationCanary"/>
        public static byte[] GenerateVerifiedOutput(AuthenticationConfiguration configuration, byte[] canary)
        {
            if (canary.IsNullOrZeroLength())
            {
                throw new ArgumentException("Canary is null or zero-length.", "canary");
            }

            Func <byte[], byte[]> validator = GetValidator(configuration, TagConstantBytes,
                                                           configuration.SerialiseDto());

            byte[] verifiedOutput = validator(canary);

            Debug.Print(DebugUtility.CreateReportString("ConfirmationUtility", "GenerateVerifiedOutput",
                                                        "Verified output",
                                                        verifiedOutput.ToHexString()));

            return(verifiedOutput);
        }
Ejemplo n.º 16
0
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);
            Xamarin.Essentials.Platform.Init(this, bundle);
            CrossCurrentActivity.Current.Init(this, bundle);
            global::Xamarin.Forms.Forms.Init(this, bundle);
            CachedImageRenderer.Init(enableFastRenderer: true);
            Xamarin.FormsMaps.Init(this, bundle);
            PlotViewRenderer.Init();
            AuthenticationConfiguration.Init(this, bundle);
            GoogleClientManager.Init(this);
            XamEffects.Droid.Effects.Init();

            LoadApplication(new App());
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Configuration related to the Thinktecture Authorization Server
        /// </summary>
        /// <returns></returns>
        private static AuthenticationConfiguration CreateAuthenticationConfiguration()
        {
            /*ClaimsAuthenticationManager = new GridsClaimsAuthenticationManager(),*/

            var authentication = new AuthenticationConfiguration
            {
                RequireSsl = false,
            };

            authentication.AddJsonWebToken(

                issuer: Constants.AuthorizationServer.IssuerName,
                audience: Constants.Audience,
                signingKey: Constants.AuthorizationServer.SigningKey,
                claimMappings: ClaimMappings.None);

            return(authentication);
        }
        public static IServiceCollection AddJwtAuthentication(
            this IServiceCollection services, AuthenticationConfiguration configuration)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = configuration.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true
                };
            });

            return(services);
        }
        public static IServiceCollection AddIdentityAuthorization(
            this IServiceCollection services, AuthenticationConfiguration configuration)
        {
            services.AddIdentity <User, IdentityRole>(o =>
            {
                o.Password.RequireDigit           = false;
                o.Password.RequireLowercase       = false;
                o.Password.RequireUppercase       = false;
                o.Password.RequireNonAlphanumeric = false;
                o.Password.RequiredLength         = 6;
            })
            .AddEntityFrameworkStores <RentalDbContext>()
            .AddDefaultTokenProviders();

            services.AddJwtAuthentication(configuration);

            return(services);
        }
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();
                // Set the default language
                rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];

                rootFrame.NavigationFailed += OnNavigationFailed;

                Xamarin.Forms.Forms.Init(e); // requires LaunchActivatedEventArgs
                global::Xamarin.Auth._MobileServices.Presenters..AuthenticationConfiguration.Init();

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(MainPage), e.Arguments);
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }
Ejemplo n.º 21
0
        private static AuthenticationConfiguration CreateAuthenticationConfiguration()
        {
            var authentication = new AuthenticationConfiguration
            {
                ClaimsAuthenticationManager = new ClaimsTransformer(),
                RequireSsl         = false,
                EnableSessionToken = true
            };

            #region Basic Authentication
            authentication.AddBasicAuthentication(UserCredentials.Validate);
            #endregion

            #region IdentityServer JWT
            authentication.AddJsonWebToken(
                issuer: Constants.IdSrv.IssuerUri,
                audience: Constants.Audience,
                signingKey: Constants.IdSrv.SigningKey);
            #endregion

            #region Access Control Service JWT
            authentication.AddJsonWebToken(
                issuer: Constants.ACS.IssuerUri,
                audience: Constants.Audience,
                signingKey: Constants.ACS.SigningKey,
                scheme: Constants.ACS.Scheme);
            #endregion

            #region IdentityServer SAML
            authentication.AddSaml2(
                issuerThumbprint: Constants.IdSrv.SigningCertThumbprint,
                issuerName: Constants.IdSrv.IssuerUri,
                audienceUri: Constants.Realm,
                certificateValidator: X509CertificateValidator.None,
                options: AuthenticationOptions.ForAuthorizationHeader(Constants.IdSrv.SamlScheme),
                scheme: AuthenticationScheme.SchemeOnly(Constants.IdSrv.SamlScheme));
            #endregion

            #region Client Certificates
            authentication.AddClientCertificate(ClientCertificateMode.ChainValidation);
            #endregion

            return(authentication);
        }
Ejemplo n.º 22
0
        public DefaultAdapter(
            BotSettings settings,
            ICredentialProvider credentialProvider,
            IChannelProvider channelProvider,
            AuthenticationConfiguration authConfig,
            LocaleTemplateManager templateEngine,
            ConversationState conversationState,
            TelemetryInitializerMiddleware telemetryMiddleware,
            IBotTelemetryClient telemetryClient,
            ILogger <BotFrameworkHttpAdapter> logger,
            IStorage storage,
            UserState userState,
            IConfiguration configuration,
            SkillConversationIdFactoryBase skillConversationIdFactoryBase,
            BotFrameworkClient botFrameworkClient)
            : base(credentialProvider, authConfig, channelProvider, logger: logger)
        {
            _conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
            _logger            = logger ?? throw new ArgumentNullException(nameof(logger));
            _templateEngine    = templateEngine ?? throw new ArgumentNullException(nameof(templateEngine));
            _telemetryClient   = telemetryClient ?? throw new ArgumentNullException(nameof(telemetryClient));
            _skillConversationIdFactoryBase = skillConversationIdFactoryBase;

            OnTurnError = HandleTurnErrorAsync;

            Use(telemetryMiddleware);

            // Uncomment the following line for local development without Azure Storage
            Use(new TranscriptLoggerMiddleware(new MemoryTranscriptStore()));
            //Use(new TranscriptLoggerMiddleware(new AzureBlobTranscriptStore(settings.BlobStorage.ConnectionString, settings.BlobStorage.Container)));
            Use(new TelemetryLoggerMiddleware(telemetryClient, logPersonalInformation: true));
            Use(new ShowTypingMiddleware());
            Use(new SetLocaleMiddleware(settings.DefaultLocale ?? "en-us"));
            Use(new EventDebuggerMiddleware());
            Use(new SetSpeakMiddleware());
            Use(new RegisterClassMiddleware <SkillConversationIdFactoryBase>(_skillConversationIdFactoryBase));
            Use(new RegisterClassMiddleware <BotFrameworkClient>(botFrameworkClient));

            //from instructions: https://microsoft.github.io/botframework-solutions/skills/handbook/experimental-add-composer/
            this.Use(new RegisterClassMiddleware <IConfiguration>(configuration));
            this.UseStorage(storage);
            this.UseBotState(userState);
            this.UseBotState(conversationState);
        }
Ejemplo n.º 23
0
        public void KeyConfirmationTest()
        {
            var inputObj = new AuthenticationConfiguration()
            {
                FunctionName          = "TestForNow",
                FunctionConfiguration = new byte[] { 0x01, 0x02, 0x03 },
                Salt           = new byte[] { 0x03, 0x01, 0x04 },
                AdditionalData = new byte[] { 0x03, 0x01, 0x04 }
            };

            var stream = SerialiseToMemory(inputObj);

            stream.Seek(0, SeekOrigin.Begin);
            var outputObj = DeserialiseFromMemory <AuthenticationConfiguration>(stream);

            bool equal = inputObj.Equals(outputObj);

            Assert.IsTrue(equal);
        }
Ejemplo n.º 24
0
        public void Configuration(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            var authenticationConfiguration = new AuthenticationConfiguration
            {
                RequireSsl = false
            };

            authenticationConfiguration.AddBasicAuthentication((userName, password) =>
            {
                return(userName == "filip" && password == "abc");
            }, AuthenticationOptions.ForHeader("MyAuthorization"));

            config.MessageHandlers.Add(new AuthenticationHandler(authenticationConfiguration));
            appBuilder.UseWebApi(config);
        }
Ejemplo n.º 25
0
        public void config(IServiceCollection services)
        {
            JwtSetting.Audience          = Configuration.GetSection("JwtTokenValues")["audience"].ToString();
            JwtSetting.Issuer            = Configuration.GetSection("JwtTokenValues")["issuer"].ToString();
            JwtSetting.SecreteKey        = Configuration.GetSection("JwtTokenValues")["securityKey"].ToString();
            JwtSetting.ExpairesInMinutes = Convert.ToInt32(Configuration.GetSection("JwtTokenValues")["expairesInMinutes"]);

            EFConfiguration.ConfigureService(services, Configuration);
            AspNetIdentityConfiguration.ConfigureService(services, Configuration);
            AuthenticationConfiguration.ConfigureService(services, Configuration);
            IocConfigurationRepository.ConfigureService(services, Configuration);
            IocConfigurationService.ConfigureService(services, Configuration);

            services.AddTransient <IDataBaseManager, DataBaseManager>();
            services.AddScoped(
                x => new ConnectionSetting(Configuration.GetConnectionString("DefaultConnection"))
                );
            services.AddScoped <SpHelper>();
        }
Ejemplo n.º 26
0
        private void RegisterAuth(HttpConfiguration config)
        {
            // NOTE: You need to get into the ASP.NET Web API pipeline
            // in order to retrieve the session token.
            // e.g: GET /token should get you the token but instead you get 404.
            // but GET /api/token works as you are inside the ASP.NET Web API pipeline now.

            var auth = new AuthenticationConfiguration {
                RequireSsl = false,
                // ClaimsAuthenticationManager = new ClaimsTransformer(),
                DefaultAuthenticationScheme = "Basic",
                EnableSessionToken          = true // default lifetime is 10 hours
            };

            auth.AddBasicAuthentication(IsValid);
            var authHandler = new AuthenticationHandler(auth);

            config.MessageHandlers.Add(authHandler);
        }
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            var authConfig = new AuthenticationConfiguration
            {
                InheritHostClientIdentity   = true,
                ClaimsAuthenticationManager = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager
            };

            // setup authentication against membership
            authConfig.AddBasicAuthentication((userName, password) => Membership.ValidateUser(userName, password));

            config.MessageHandlers.Add(new AuthenticationHandler(authConfig));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="BotFrameworkHttpAdapter"/> class.
        /// </summary>
        /// <param name="configuration">An <see cref="IConfiguration"/> instance.</param>
        /// <param name="credentialProvider">The credential provider.</param>
        /// <param name="authConfig">The authentication configuration.</param>
        /// <param name="channelProvider">The channel provider.</param>
        /// <param name="connectorClientRetryPolicy">Retry policy for retrying HTTP operations.</param>
        /// <param name="customHttpClient">The HTTP client.</param>
        /// <param name="middleware">The middleware to initially add to the adapter.</param>
        /// <param name="logger">The ILogger implementation this adapter should use.</param>
        protected BotFrameworkHttpAdapter(
            IConfiguration configuration,
            ICredentialProvider credentialProvider,
            AuthenticationConfiguration authConfig = null,
            IChannelProvider channelProvider       = null,
            RetryPolicy connectorClientRetryPolicy = null,
            HttpClient customHttpClient            = null,
            IMiddleware middleware = null,
            ILogger logger         = null)
            : this(credentialProvider ?? new ConfigurationCredentialProvider(configuration), authConfig ?? new AuthenticationConfiguration(), channelProvider ?? new ConfigurationChannelProvider(configuration), connectorClientRetryPolicy, customHttpClient, middleware, logger)
        {
            var openIdEndpoint = configuration.GetSection(AuthenticationConstants.BotOpenIdMetadataKey)?.Value;

            if (!string.IsNullOrEmpty(openIdEndpoint))
            {
                // Indicate which Cloud we are using, for example, Public or Sovereign.
                ChannelValidation.OpenIdMetadataUrl           = openIdEndpoint;
                GovernmentChannelValidation.OpenIdMetadataUrl = openIdEndpoint;
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BotFrameworkSkillHostAdapter"/> class,
        /// using a credential provider.
        /// </summary>
        /// <param name="adapter">adapter that this skillAdapter is bound to.</param>
        /// <param name="credentialProvider">The credential provider.</param>
        /// <param name="authConfig">The authentication configuration.</param>
        /// <param name="channelProvider">The channel provider.</param>
        /// <param name="connectorClientRetryPolicy">Retry policy for retrying HTTP operations.</param>
        /// <param name="customHttpClient">The HTTP client.</param>
        /// <param name="logger">The ILogger implementation this adapter should use.</param>
        /// <exception cref="ArgumentNullException">throw ArgumentNullException.</exception>
        /// <remarks>Use a <see cref="MiddlewareSet"/> object to add multiple middleware
        /// components in the constructor. Use the Use(<see cref="IMiddleware"/>) method to
        /// add additional middleware to the adapter after construction.
        /// </remarks>
        public BotFrameworkSkillHostAdapter(
            BotAdapter adapter,
            ICredentialProvider credentialProvider,
            AuthenticationConfiguration authConfig,
            IChannelProvider channelProvider       = null,
            RetryPolicy connectorClientRetryPolicy = null,
            HttpClient customHttpClient            = null,
            ILogger logger = null)
            : base(adapter, logger)
        {
            _credentialProvider         = credentialProvider ?? throw new ArgumentNullException(nameof(credentialProvider));
            _channelProvider            = channelProvider;
            _httpClient                 = customHttpClient ?? _defaultHttpClient;
            _connectorClientRetryPolicy = connectorClientRetryPolicy;
            _logger            = logger ?? NullLogger.Instance;
            _authConfiguration = authConfig ?? throw new ArgumentNullException(nameof(authConfig));

            // DefaultRequestHeaders are not thread safe so set them up here because this adapter should be a singleton.
            ConnectorClient.AddDefaultRequestHeaders(_httpClient);
        }
Ejemplo n.º 30
0
        public static AuthenticationConfiguration Create(Oauth2AuthenticationSettings oauth2AuthenticationSettings, ILogger logger)
        {
            _logger = logger;
            _oauth2AuthenticationSettings = oauth2AuthenticationSettings;

            var authentication = new AuthenticationConfiguration
            {
                ClaimsAuthenticationManager = new ProvisioningClaimsAuthenticationManager(GetClaimsForUser),
                RequireSsl         = !AuthenticationConstants.AllowInsecureHttp,
                EnableSessionToken = true
            };

            #region Basic Authentication

            authentication.AddBasicAuthentication(AuthenticateUser);

            #endregion

            return(authentication);
        }
Ejemplo n.º 31
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            AuthenticationConfiguration authenticationConfiguration = new AuthenticationConfiguration();

            _configuration.Bind("Authentication", authenticationConfiguration);
            services.AddSingleton(authenticationConfiguration);

            services.AddSingleton <IPasswordHasher, BCryptPasswordHasher>();
            services.AddSingleton <IUserRepository, InMemoryUserRepository>();
            services.AddSingleton <IRefreshTokenRepository, InMemoryRefreshTokenRepository>();
            services.AddSingleton <Authenticator>();

            services.AddSingleton <TokenGenerator>();
            services.AddSingleton <AccessTokenGenerator>();
            services.AddSingleton <RefreshTokenGenerator>();

            services.AddSingleton <RefreshTokenValidator>();
        }
        public static void AddMsftJsonWebToken(this AuthenticationConfiguration configuration, string issuer, string audience, X509Certificate2 signingCertificate)
        {
            var validationParameters = new TokenValidationParameters()
            {
                AllowedAudience    = audience,
                SigningToken       = new X509SecurityToken(signingCertificate),
                ValidIssuer        = issuer,
                ValidateExpiration = true
            };

            var handler = new JWTSecurityTokenHandlerWrapper(validationParameters);

            configuration.AddMapping(new AuthenticationOptionMapping {
                TokenHandler = new SecurityTokenHandlerCollection {
                    handler
                },
                Options = AuthenticationOptions.ForAuthorizationHeader(JwtConstants.Bearer),
                Scheme  = AuthenticationScheme.SchemeOnly(JwtConstants.Bearer)
            });
        }
Ejemplo n.º 33
0
        public void Arrange()
        {
            _authenticationConfiguration = new AuthenticationConfiguration()
            {
                ClientId      = "some client id",
                ClientSecret  = "some secret",
                Resource      = "http://some.fake.url/abc123",
                TokenEndpoint = "https://somecorp.local/tokens",
            };

            _restClientMock = new Mock <IRestClient>();
            _restClientMock.Setup(c => c.ExecuteTaskAsync(It.IsAny <IRestRequest>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new RestResponse
            {
                StatusCode     = HttpStatusCode.NotFound,
                ResponseStatus = ResponseStatus.Completed,
            });

            _cacheProviderMock = new Mock <ICacheProvider>();

            _configuration = new TranslatorConfiguration
            {
                BaseUrl = "https://translator.unit.tests",
            };

            _loggerMock = new Mock <ILoggerWrapper>();

            _spiExecutionContextManagerMock = new Mock <ISpiExecutionContextManager>();
            _spiExecutionContextManagerMock.Setup(x => x.SpiExecutionContext)
            .Returns(new SpiExecutionContext());

            _translator = new TranslatorApiClient(
                _authenticationConfiguration,
                _restClientMock.Object,
                _cacheProviderMock.Object,
                _configuration,
                _loggerMock.Object,
                _spiExecutionContextManagerMock.Object);

            _cancellationToken = new CancellationToken();
        }
Ejemplo n.º 34
0
        public static void Register(HttpConfiguration config)
        {
            var idsvrId = "http://idsrv.local/trust";
            var cert    = X509.LocalMachine.TrustedPeople.SubjectDistinguishedName.Find("CN=sts", false).Single();

            {
                var authConfig = new AuthenticationConfiguration();
                authConfig.AddMsftJsonWebToken(
                    idsvrId,
                    "http://localhost/rp-adfs-webapi1",
                    cert);

                var authHandler = new AuthenticationHandler(authConfig, config);

                config.Routes.MapHttpRoute(
                    name: "test1",
                    routeTemplate: "api/test1",
                    defaults: new { controller = "Test1" },
                    constraints: null,
                    handler: authHandler
                    );
            }

            {
                var authConfig = new AuthenticationConfiguration();
                authConfig.AddMsftJsonWebToken(
                    idsvrId,
                    "http://localhost/rp-adfs-webapi2",
                    cert);

                var authHandler = new AuthenticationHandler(authConfig, config);

                config.Routes.MapHttpRoute(
                    name: "test2",
                    routeTemplate: "api/test2",
                    defaults: new { controller = "Test2" },
                    constraints: null,
                    handler: authHandler
                    );
            }
        }
Ejemplo n.º 35
0
        public static void ConfigureOAuth()
        {
            // Create ACS OAuth filter
            var authenticationConfiguration = new AuthenticationConfiguration
            {
                RequireSsl = false,
                ClaimsAuthenticationManager = new ClaimsTransformer()
            };

            authenticationConfiguration.AddJsonWebToken(
                issuer: "https://eyecatch.accesscontrol.windows.net/",
                audience: "http://localhost:61390/",
                signingKey: "vZhjuby4hTmoaKnptAXe1MPAMiI+63obW20+fVaFAYM=",
                scheme: "ACS");

            // Use custom acs controller factory
            ControllerBuilder.Current.SetControllerFactory(
                new AcsControllerFactory(
                    new CookieToAuthenticationHeaderHandler("ACS"),
                    new AuthenticationHandler(authenticationConfiguration, new HttpRequestMessageFactory())));
        }
        public static AuthenticationConfiguration CreateBasicAuthConfig(IUserRepository userRepository)
        {
            var authConfig = new AuthenticationConfiguration
            {
                InheritHostClientIdentity = false,
                DefaultAuthenticationScheme = "Basic",
                ClaimsAuthenticationManager = new ClaimsTransformer()
            };

            authConfig.AddBasicAuthentication((userName, password) => userRepository.ValidateUser(userName, password));
            return authConfig;
        }
Ejemplo n.º 37
0
        public static AuthenticationConfiguration CreateClientAuthConfig(HttpConfiguration httpConfiguration, IConfigurationRepository configuration)
        {
            _logger.Info("Creating client auth configuration... ");
            var authConfig = new AuthenticationConfiguration
            {
                InheritHostClientIdentity = false,
                RequireSsl = false,
                //EnableSessionToken = true,
               // DefaultAuthenticationScheme = JwtConstants.JWT,
            };

            // accept arbitrary credentials on basic auth header,
            // validation will be done in the protocol endpoint
            authConfig.AddBasicAuthentication((id, secret) => true, retainPassword: true);
            authConfig.AddJsonWebToken(
                issuer: configuration.Global.IssuerUri,
                audience: FACCTS.Server.Common.Constants.RelyingParties.FACCTS,
                signingKey: configuration.Keys.SymmetricSigningKey
                );
            httpConfiguration.MessageHandlers.Add(new AuthenticationHandler(authConfig));
            _logger.Info("Client auth configuration done! ");
            return authConfig;
        }
Ejemplo n.º 38
0
        public static AuthenticationConfiguration CreateBasicAuthConfig(IUserRepository userRepository)
        {
            _logger.Info("Creating basic auth configuration...");
            var authConfig = new AuthenticationConfiguration
            {
                InheritHostClientIdentity = false,
                //RequireSsl = true,
                ClaimsAuthenticationManager = new FACCTS.Server.Data.ClaimsTransformer()
            };

            authConfig.AddBasicAuthentication((userName, password) => userRepository.ValidateUser(userName, password));
            _logger.Info("Basic auth configuration done!");
            return authConfig;
        }
 public MembershipRepository(AuthenticationConfiguration config)
 {            
     // if multiple domains in place for WAAD tenant this needs to change
     _authConfig = config;
 }