Exemplo n.º 1
0
        protected async Task BaseInitializeAsync(AuthenticationOptions options, HttpContext context)
        {
            _baseOptions = options;
            Context = context;
            RequestPathBase = Request.PathBase;

            RegisterAuthenticationHandler();

            Response.OnSendingHeaders(OnSendingHeaderCallback, this);

            await InitializeCoreAsync();

            if (BaseOptions.AuthenticationMode == AuthenticationMode.Active)
            {
                AuthenticationTicket ticket = await AuthenticateAsync();
                if (ticket != null && ticket.Identity != null)
                {
                    SecurityHelper.AddUserIdentity(Context, ticket.Identity);
                }
            }
        }
Exemplo n.º 2
0
        protected async Task BaseInitialize(AuthenticationOptions options, OwinRequest request, OwinResponse response)
        {
            _baseOptions = options;
            Request = request;
            Response = response;
            Helper = new SecurityHelper(request);
            RequestPathBase = Request.PathBase;

            _registration = Request.RegisterAuthenticationHandler(this);

            Request.OnSendingHeaders(state => ((AuthenticationHandler)state).ApplyResponse().Wait(), this);

            await InitializeCore();

            if (BaseOptions.AuthenticationMode == AuthenticationMode.Active)
            {
                AuthenticationTicket ticket = await Authenticate();
                if (ticket != null && ticket.Identity != null)
                {
                    Helper.AddUserIdentity(ticket.Identity);
                }
            }
        }
Exemplo n.º 3
0
 private static void GetAuthenticationOptions(AuthenticationOptions options)
 {
     options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
 }
        private async Task AfterInitialAuthDialog(
            IDialogContext authContext,
            IAwaitable <AuthResult> awaitableAuthResult)
        {
            try
            {
                SD.Trace.TraceInformation("AppAuthDialog::AfterInitialAuthDialog");

                AuthResult authResult = await awaitableAuthResult;
                Activity   activity   = authContext.ConversationData.GetValue <Activity>("Activity");

                // return our reply to the user for debugging purposes
                if (displayAuthMessages)
                {
                    int length = (activity.Text ?? string.Empty).Length;
                    await authContext.PostAsync($"We see you sent {activity.Text} which was {length} characters");
                }

                if (authResult == null)
                {
                    await authContext.PostAsync("You didn't log in.");

                    authContext.Done(true);
                    return;
                }
                else
                {
                    if (displayAuthMessages)
                    {
                        await authContext.PostAsync($"Token: {authResult.AccessToken}");
                    }
                }

                // Use token to call into service
                JObject json = await new HttpClient().GetWithAuthAsync(
                    authResult.AccessToken, GraphUrl);

                // Two items to test
                // A -- Access Token Expires, do JUST [Part 1] Below
                // B -- Access Token Expires AND refresh fails, do [Part 1], [Part 2], and [Part 3].
                //
                // To test auth expiration null out json variable (uncomment next line) [Part 1]
                // json = null;
                if (json == null)
                {
                    var authProvider = new MSALAuthProvider();
                    AuthenticationOptions options =
                        authContext.UserData.GetValue <AuthenticationOptions>(
                            $"{authProvider.Name}{ContextConstants.AuthOptions}");

                    SD.Trace.TraceInformation("Attempting to refresh with token.");
                    if (displayAuthMessages)
                    {
                        await authContext.PostAsync($"Attempting to refresh with token: {authResult.RefreshToken}");
                    }

                    // To test auth expiration comment out next line [Part 2]
                    authResult = await authProvider.GetAccessToken(options, authContext);

                    // To test auth expiration uncomment out next two lines [Part 3]
                    // authResult = null;
                    // await authProvider.Logout(options, authContext);
                    if (authResult != null)
                    {
                        SD.Trace.TraceInformation("Token Refresh Succeeded.");
                        if (displayAuthMessages)
                        {
                            await authContext.PostAsync($"Token Refresh Succeeded. New Token: {authResult.AccessToken}");
                        }
                        json = await new HttpClient().GetWithAuthAsync(
                            authResult.AccessToken, "https://graph.microsoft.com/v1.0/me");
                    }
                    else
                    {
                        SD.Trace.TraceInformation("Token Refresh Failed. Trying full login.");

                        if (displayAuthMessages)
                        {
                            await authContext.PostAsync("Token Refresh Failed. Trying full login.");
                        }
                        await authContext.Forward(
                            new BotAuth.Dialogs.AuthDialog(new MSALAuthProvider(), options),
                            this.AfterInitialAuthDialog,
                            activity,
                            CancellationToken.None);

                        return;
                    }
                }

                SD.Trace.TraceInformation("Getting user data post auth.");
                string userName  = json.Value <string>("displayName");
                string userEmail = json.Value <string>("userPrincipalName");

                if (displayAuthMessages)
                {
                    await authContext.PostAsync($"I now know your name is {userName} " +
                                                $"and your UPN is {userEmail}");
                }

                MeetingRequestInput meetingData = authContext.ConversationData.GetValue <MeetingRequestInput>(MeetingDataKey);
                meetingData.OrganizerName  = userName;
                meetingData.OrganizerEmail = userEmail;

                authContext.ConversationData.SetValue(MeetingDataKey, meetingData);
                authContext.PrivateConversationData.SetValue(AccessTokenDataKey, authResult.AccessToken);

                SD.Trace.TraceInformation("Post Auth Hand Off to CreateMeetingRequestDialog.");
                authContext.Call(new CreateMeetingRequestDialog(), this.ResumeAfterMeetingDialog);
            }
            catch (Exception ex)
            {
                string fullError = ex.ToString();
                SD.Trace.TraceError(fullError);
                await authContext.PostAsync(fullError);
            }
        }
 private static void AuthenticationOptionsConfigure(AuthenticationOptions opts)
 {
     opts.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
     opts.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
     opts.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
 }
Exemplo n.º 6
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">IServiceCollection instance.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            // Add all options set from configuration values.
            services.AddOptions <AuthenticationOptions>()
            .Configure <IConfiguration>((authenticationOptions, configuration) =>
            {
                Startup.FillAuthenticationOptionsProperties(authenticationOptions, configuration);
            });
            services.AddOptions <BotOptions>()
            .Configure <IConfiguration>((botOptions, configuration) =>
            {
                botOptions.MicrosoftAppId       = configuration.GetValue <string>("MicrosoftAppId");
                botOptions.MicrosoftAppPassword = configuration.GetValue <string>("MicrosoftAppPassword");
            });
            services.AddOptions <BotFilterMiddlewareOptions>()
            .Configure <IConfiguration>((botFilterMiddlewareOptions, configuration) =>
            {
                botFilterMiddlewareOptions.DisableTenantFilter =
                    configuration.GetValue <bool>("DisableTenantFilter", false);
                botFilterMiddlewareOptions.AllowedTenants =
                    configuration.GetValue <string>("AllowedTenants");
            });
            services.AddOptions <RepositoryOptions>()
            .Configure <IConfiguration>((repositoryOptions, configuration) =>
            {
                repositoryOptions.StorageAccountConnectionString =
                    configuration.GetValue <string>("StorageAccountConnectionString");

                // Setting this to false because the main application should ensure that all
                // tables exist.
                repositoryOptions.IsItExpectedThatTableAlreadyExists = false;
            });
            services.AddOptions <MessageQueueOptions>()
            .Configure <IConfiguration>((messageQueueOptions, configuration) =>
            {
                messageQueueOptions.ServiceBusConnection =
                    configuration.GetValue <string>("ServiceBusConnection");
            });
            services.AddOptions <DataQueueMessageOptions>()
            .Configure <IConfiguration>((dataQueueMessageOptions, configuration) =>
            {
                dataQueueMessageOptions.ForceCompleteMessageDelayInSeconds =
                    configuration.GetValue <double>("ForceCompleteMessageDelayInSeconds", 86400);
            });
            services.AddOptions();

            // Add localization services.
            services.AddLocalization();

            // Add authentication services.
            AuthenticationOptions authenticationOptionsParameter = new AuthenticationOptions();

            Startup.FillAuthenticationOptionsProperties(authenticationOptionsParameter, this.Configuration);
            services.AddAuthentication(this.Configuration, authenticationOptionsParameter);
            services.AddControllersWithViews();

            // Setup SPA static files.
            // In production, the React files will be served from this directory.
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });

            // Add blob client.
            services.AddSingleton(sp => new BlobContainerClient(
                                      sp.GetService <IConfiguration>().GetValue <string>("StorageAccountConnectionString"),
                                      Common.Constants.BlobContainerName));

            // The bot needs an HttpClient to download and upload files.
            services.AddHttpClient();

            // Add bot services.
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();
            services.AddTransient <CompanyCommunicatorBotFilterMiddleware>();
            services.AddSingleton <CompanyCommunicatorBotAdapter>();
            services.AddTransient <TeamsDataCapture>();
            services.AddTransient <TeamsFileUpload>();
            services.AddTransient <IBot, CompanyCommunicatorBot>();

            // Add repositories.
            services.AddSingleton <TeamDataRepository>();
            services.AddSingleton <UserDataRepository>();
            services.AddSingleton <SentNotificationDataRepository>();
            services.AddSingleton <NotificationDataRepository>();
            services.AddSingleton <SendBatchesDataRepository>();
            services.AddSingleton <ExportDataRepository>();

            // Add service bus message queues.
            services.AddSingleton <PrepareToSendQueue>();
            services.AddSingleton <DataQueue>();
            services.AddSingleton <ExportQueue>();

            // Add draft notification preview services.
            services.AddTransient <DraftNotificationPreviewService>();

            // Add microsoft graph services.
            services.AddTransient <IGraphServiceClient, GraphServiceClient>();
            services.AddTransient <IAuthenticationProvider, GraphTokenProvider>();
            services.AddScoped <IGroupsService, GroupsService>();

            // Add Application Insights telemetry.
            services.AddApplicationInsightsTelemetry();

            // Add miscellaneous dependencies.
            services.AddTransient <TableRowKeyGenerator>();
            services.AddTransient <AdaptiveCardCreator>();
        }
Exemplo n.º 7
0
        private static async Task <ClaimsPrincipal> ValidateTokenAsync(this AuthenticationHeaderValue value, AuthenticationOptions securityOptions, ILogger logger = null)
        {
            if (value?.Scheme != "Bearer")
            {
                return(null);
            }

            var configurationManager = new ConfigurationManager <OpenIdConnectConfiguration>(
                $"{securityOptions.Issuer}/.well-known/openid-configuration",
                new OpenIdConnectConfigurationRetriever(),
                new HttpDocumentRetriever {
                RequireHttps = securityOptions.Issuer.StartsWith("https://")
            }
                );
            var config = await configurationManager.GetConfigurationAsync(CancellationToken.None);

            var validationParameter = new TokenValidationParameters
            {
                RequireSignedTokens      = true,
                ValidAudience            = securityOptions.Audience,
                ValidateAudience         = true,
                ValidIssuer              = $"{securityOptions.Issuer}/", // Auth0's issuer has a '/' on the end of its url
                ValidateIssuer           = true,
                ValidateIssuerSigningKey = true,
                ValidateLifetime         = true,
                IssuerSigningKeys        = config.SigningKeys,
                ValidateActor            = true
            };

            ClaimsPrincipal result = null;
            var             tries  = 0;

            while (result == null && tries <= 1)
            {
                try
                {
                    var handler = new JwtSecurityTokenHandler();
                    result = handler.ValidateToken(value.Parameter, validationParameter, out var token);
                }
                catch (SecurityTokenSignatureKeyNotFoundException ex1)
                {
                    logger?.LogWarning($"{nameof(SecurityTokenSignatureKeyNotFoundException)}: {ex1.Message}");

                    // This exception is thrown if the signature key of the JWT could not be found.
                    // This could be the case when the issuer changed its signing keys, so we trigger a
                    // refresh and retry validation.
                    configurationManager.RequestRefresh();
                    tries++;
                }
                catch (SecurityTokenException ex2)
                {
                    logger?.LogWarning($"{nameof(SecurityTokenException)}: {ex2.Message}");

                    return(null);
                }
            }

            return(result);
        }
 private void ThenTheFollowingConfigIsReturned(AuthenticationOptions expected)
 {
     _result.AllowedScopes.ShouldBe(expected.AllowedScopes);
     _result.AuthenticationProviderKey.ShouldBe(expected.AuthenticationProviderKey);
 }
Exemplo n.º 9
0
 public static void Setup(AuthenticationOptions options)
 {
     options.DefaultAuthenticateScheme = OverseerAuthenticationScheme;
     options.DefaultChallengeScheme    = OverseerAuthenticationScheme;
 }
Exemplo n.º 10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // ReSharper disable once UnusedMember.Global
        public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigureOptions(Configuration, typeof(NethereumOptions), typeof(AuthenticationOptions), typeof(SiteOptions), typeof(SmtpOptions), typeof(AzureStorageOptions));

            services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info {
                    Title = "SmartValley API", Version = "v1"
                }); });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = _currentEnvironment.IsProduction();
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = AuthenticationOptions.Issuer,
                    ValidateAudience         = true,
                    ValidAudience            = AuthenticationOptions.Audience,
                    ValidateLifetime         = false,
                    IssuerSigningKey         = AuthenticationOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true
                };
            });

            services.AddSingleton(provider => InitializeWeb3(provider.GetService <NethereumOptions>().RpcAddress));
            services.AddSingleton <IClock, UtcClock>();
            services.AddSingleton <EthereumMessageSigner>();
            services.AddSingleton <EthereumClient>();
            services.AddSingleton <EthereumContractClient>();
            services.AddSingleton <MailService>();
            services.AddSingleton <MailTokenService>();
            services.AddSingleton <MailSender>();
            services.AddSingleton <ITemplateProvider, TemplateProvider>(provider => new TemplateProvider(_currentEnvironment.ContentRootPath));
            services.AddSingleton(InitializeProjectTeamMembersStorageProvider);
            services.AddSingleton(InitializeApplicationTeamMembersStorageProvider);
            services.AddSingleton(InitializeExpertApplicationsStorageProvider);
            services.AddSingleton(InitializeProjectStorageProvider);
            services.AddSingleton <IScoringContractClient, ScoringContractClient>(
                provider => new ScoringContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().ScoringContract));
            services.AddSingleton <IERC223ContractClient, ERC223ContractClient>(
                provider => new ERC223ContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().ERC223Contract));
            services.AddSingleton <IEtherManagerContractClient, EtherManagerContractClient>(
                provider => new EtherManagerContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().EtherManagerContract));
            services.AddSingleton <IScoringsRegistryContractClient, ScoringsRegistryContractClient>(
                provider => new ScoringsRegistryContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().ScoringsRegistryContract));
            services.AddSingleton <IScoringOffersManagerContractClient, ScoringOffersManagerContractClient>(
                provider => new ScoringOffersManagerContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().ScoringOffersManagerContract));
            services.AddSingleton <IAllotmentEventsManagerContractClient, AllotmentEventsManagerContractClient>(
                provider => new AllotmentEventsManagerContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().AllotmentEventsManagerContract));
            services.AddSingleton <IAllotmentEventContractClient, AllotmentEventContractClient>(
                provider => new AllotmentEventContractClient(provider.GetService <EthereumContractClient>(), provider.GetService <NethereumOptions>().AllotmentEventContract.Abi));

            services.AddMemoryCache();

            services.AddMvc(options =>
            {
                options.Filters.Add(new AuthenticationFilterFactory());
                options.Filters.Add(new AppErrorsExceptionFilter());
                options.Filters.Add(new ModelStateFilter());
            });

            var builder = new DbContextOptionsBuilder <AppDBContext>();

            builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            var dbOptions = builder.Options;

            services.AddDbContext <AppDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddTransient(x => AppDBContext.CreateEditable(dbOptions));
            services.AddTransient(x => AppDBContext.CreateReadOnly(dbOptions));
            services.AddTransient <IProjectRepository, ProjectRepository>();
            services.AddTransient <IScoringRepository, ScoringRepository>();
            services.AddTransient <IScoringOffersRepository, ScoringOffersRepository>();
            services.AddTransient <IProjectService, ProjectService>();
            services.AddTransient <IEstimationService, EstimationService>();
            services.AddTransient <IScoringService, ScoringService>();
            services.AddTransient <IScoringCriterionRepository, ScoringCriterionRepository>();
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IUserService, UserService>();
            services.AddTransient <IAdminService, AdminService>();
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IAuthenticationService, AuthenticationService>();
            services.AddTransient <IExpertRepository, ExpertRepository>();
            services.AddTransient <IExpertService, ExpertService>();
            services.AddTransient <Experts.IExpertService, Experts.ExpertService>();
            services.AddTransient <IExpertApplicationRepository, ExpertApplicationRepository>();
            services.AddTransient <ICountryRepository, CountryRepository>();
            services.AddTransient <IExpertApplicationRepository, ExpertApplicationRepository>();
            services.AddTransient <IScoringApplicationRepository, ScoringApplicationRepository>();
            services.AddTransient <IScoringApplicationQuestionsRepository, ScoringApplicationQuestionsRepository>();
            services.AddTransient <IScoringApplicationService, ScoringApplicationService>();
            services.AddTransient <IFeedbackRepository, FeedbackRepository>();
            services.AddTransient <IFeedbackService, FeedbackService>();
            services.AddTransient <IAllotmentEventService, AllotmentEventService>();
            services.AddTransient <IAllotmentEventRepository, AllotmentEventRepository>();
            services.AddTransient <IEthereumTransactionService, EthereumTransactionService>();
            services.AddTransient <IEthereumTransactionRepository, EthereumTransactionRepository>();

            var logger = CreateLogger();

            services.AddSingleton(logger.ForContext("Source", "api"));

            var serviceProvider = services.BuildServiceProvider();
            var siteOptions     = serviceProvider.GetService <SiteOptions>();

            ConfigureCorsPolicy(services, siteOptions);

            var dataProtectionProvider = serviceProvider.GetService <IDataProtectionProvider>();

            services.AddSingleton <IMessageSession>(
                provider => EndpointConfigurator
                .StartAsync(Configuration, _currentEnvironment.ContentRootPath, dataProtectionProvider, logger.ForContext("Source", "nservicebus"))
                .GetAwaiter()
                .GetResult());
        }
        public Response <RequestDelegate> CreateIdentityServerAuthenticationHandler(IApplicationBuilder app, AuthenticationOptions authOptions)
        {
            var builder = app.New();

            builder.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
            {
                Authority            = authOptions.ProviderRootUrl,
                ApiName              = authOptions.ScopeName,
                RequireHttpsMetadata = authOptions.RequireHttps,
                AllowedScopes        = authOptions.AdditionalScopes,
                SupportedTokens      = SupportedTokens.Both,
                ApiSecret            = authOptions.ScopeSecret
            });

            var authenticationNext = builder.Build();

            return(new OkResponse <RequestDelegate>(authenticationNext));
        }
Exemplo n.º 12
0
        public async Task SearchFiles(IDialogContext context, LuisResult result)
        {
            // makes sure we got at least one entity from LUIS
            if (result.Entities.Count == 0)
            {
                await None(context, result);
            }
            else
            {
                var query = "https://graph.microsoft.com/v1.0/me/drive/search(q='{0}')?$select=id,name,size,webUrl&$top=5";
                // we will assume only one entity, but LUIS can handle multiple entities
                if (result.Entities[0].Type == "FileName")
                {
                    // perform a search for the filename
                    query = String.Format(query, result.Entities[0].Entity.Replace(" . ", "."));
                }
                else if (result.Entities[0].Type == "FileType")
                {
                    // perform search based on filetype...but clean up the filetype first
                    var           fileType = result.Entities[0].Entity.Replace(" . ", ".").Replace(". ", ".").ToLower();
                    List <string> images   = new List <string>()
                    {
                        "images", "pictures", "pics", "photos", "image", "picture", "pic", "photo"
                    };
                    List <string> presentations = new List <string>()
                    {
                        "powerpoints", "presentations", "decks", "powerpoints", "presentation", "deck", ".pptx", ".ppt", "pptx", "ppt"
                    };
                    List <string> documents = new List <string>()
                    {
                        "documents", "document", "word", "doc", ".docx", ".doc", "docx", "doc"
                    };
                    List <string> workbooks = new List <string>()
                    {
                        "workbooks", "workbook", "excel", "spreadsheet", "spreadsheets", ".xlsx", ".xls", "xlsx", "xls"
                    };
                    List <string> music = new List <string>()
                    {
                        "music", "songs", "albums", ".mp3", "mp3"
                    };
                    List <string> videos = new List <string>()
                    {
                        "video", "videos", "movie", "movies", ".mp4", "mp4", ".mov", "mov", ".avi", "avi"
                    };

                    if (images.Contains(fileType))
                    {
                        query = String.Format(query, ".png .jpg .jpeg .gif");
                    }
                    else if (presentations.Contains(fileType))
                    {
                        query = String.Format(query, ".pptx .ppt");
                    }
                    else if (documents.Contains(fileType))
                    {
                        query = String.Format(query, ".docx .doc");
                    }
                    else if (workbooks.Contains(fileType))
                    {
                        query = String.Format(query, ".xlsx .xls");
                    }
                    else if (music.Contains(fileType))
                    {
                        query = String.Format(query, ".mp3");
                    }
                    else if (videos.Contains(fileType))
                    {
                        query = String.Format(query, ".mp4 .avi .mov");
                    }
                    else
                    {
                        query = String.Format(query, fileType);
                    }
                }

                // save the query so we can run it after authenticating
                context.ConversationData.SetValue <string>("GraphQuery", query);
                // Initialize AuthenticationOptions with details from AAD v2 app registration (https://apps.dev.microsoft.com)
                AuthenticationOptions options = new AuthenticationOptions()
                {
                    Authority    = ConfigurationManager.AppSettings["aad:Authority"],
                    ClientId     = ConfigurationManager.AppSettings["aad:ClientId"],
                    ClientSecret = ConfigurationManager.AppSettings["aad:ClientSecret"],
                    Scopes       = new string[] { "Files.Read" },
                    RedirectUrl  = ConfigurationManager.AppSettings["aad:Callback"]
                };

                // Forward the dialog to the AuthDialog to sign the user in and get an access token for calling the Microsoft Graph
                await context.Forward(new AuthDialog(new MSALAuthProvider(), options), async (IDialogContext authContext, IAwaitable <AuthResult> authResult) =>
                {
                    var tokenInfo = await authResult;

                    // Get the users profile photo from the Microsoft Graph
                    var json  = await new HttpClient().GetWithAuthAsync(tokenInfo.AccessToken, authContext.ConversationData.GetValue <string>("GraphQuery"));
                    var items = (JArray)json.SelectToken("value");
                    var reply = ((Activity)authContext.Activity).CreateReply();
                    foreach (var item in items)
                    {
                        // we could get thumbnails for each item using the id, but will keep it simple
                        ThumbnailCard card = new ThumbnailCard()
                        {
                            Title    = item.Value <string>("name"),
                            Subtitle = $"Size: {item.Value<int>("size").ToString()}",
                            Text     = $"Download: {item.Value<string>("webUrl")}"
                        };
                        reply.Attachments.Add(card.ToAttachment());
                    }

                    reply.AttachmentLayout = AttachmentLayoutTypes.Carousel;
                    ConnectorClient client = new ConnectorClient(new Uri(authContext.Activity.ServiceUrl));
                    await client.Conversations.ReplyToActivityAsync(reply);
                }, context.Activity, CancellationToken.None);
            }
        }
Exemplo n.º 13
0
 public EnsureSignInScheme(IOptions <AuthenticationOptions> authOptions)
 {
     _authOptions = authOptions.Value;
 }
Exemplo n.º 14
0
 private void SetJwtBearerAuthentication(AuthenticationOptions options)
 {
     options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
 }
Exemplo n.º 15
0
        public static async Task <AuthenticationStatus> Authenticate(this HttpRequest httpRequest, AuthenticationOptions securityOptions, string userId, ILogger logger = null)
        {
            if (securityOptions.Debug == true)
            {
                return(AuthenticationStatus.Authenticated); // Doing this for now because swagger isnt using jwt token
            }

            var authenticationHeader = httpRequest.ParseAuthenticationHeader(logger);

            if ((await authenticationHeader?.ValidateTokenAsync(securityOptions, logger)) == null)
            {
                return(AuthenticationStatus.Unauthenticated);
            }

            var tokenHandler = new JwtSecurityTokenHandler();

            if (!tokenHandler.CanReadToken(authenticationHeader.Parameter))
            {
                return(AuthenticationStatus.Unauthenticated);
            }

            var token = tokenHandler.ReadJwtToken(authenticationHeader.Parameter);

            if (userId != token.Subject)
            {
                return(AuthenticationStatus.Unauthenticated);
            }

            return(AuthenticationStatus.Authenticated);
        }
Exemplo n.º 16
0
        public static void Configure(IAppBuilder app, IUnityContainer container, AuthenticationOptions authenticationOptions)
        {
            app.CreatePerOwinContext(() => container.Resolve<SecurityDbContext>());
            app.CreatePerOwinContext(() => container.Resolve<ApplicationUserManager>());

            if (authenticationOptions.CookiesEnabled)
            {
                // Enable the application to use a cookie to store information for the signed in user
                // and to use a cookie to temporarily store information about a user logging in with a third party login provider
                // Configure the sign in cookie
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    //LoginPath = new PathString("/Account/Logon"),
                    Provider = new CookieAuthenticationProvider
                    {
                        // Enables the application to validate the security stamp when the user logs in.
                        // This is a security feature which is used when you change a password or add an external login to your account.  
                        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                            validateInterval: authenticationOptions.CookiesValidateInterval,
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                    }
                });
            }

            if (authenticationOptions.BearerTokensEnabled)
            {
                app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath = new PathString("/Token"),
                    AuthorizeEndpointPath = new PathString("/Account/Authorize"),
                    Provider = new ApplicationOAuthProvider(PublicClientId),
                    AccessTokenExpireTimeSpan = authenticationOptions.BearerTokensExpireTimeSpan,
                    AllowInsecureHttp = true
                });
            }

            if (authenticationOptions.HmacEnabled || authenticationOptions.ApiKeysEnabled)
            {
                var apiAccountProvider = container.Resolve<IApiAccountProvider>();
                var claimsIdentityProvider = container.Resolve<IClaimsIdentityProvider>();
                var cacheManager = container.Resolve<ICacheManager<object>>();


                if (authenticationOptions.HmacEnabled)
                {
                    app.UseHmacAuthentication(new HmacAuthenticationOptions
                    {
                        ApiCredentialsProvider = apiAccountProvider,
                        IdentityProvider = claimsIdentityProvider,
                        CacheManager = cacheManager,
                        SignatureValidityPeriod = authenticationOptions.HmacSignatureValidityPeriod
                    });
                }

                if (authenticationOptions.ApiKeysEnabled)
                {
                    app.UseApiKeysAuthentication(new ApiKeysAuthenticationOptions
                    {
                        ApiCredentialsProvider = apiAccountProvider,
                        IdentityProvider = claimsIdentityProvider,
                        CacheManager = cacheManager,
                        HttpHeaderName = authenticationOptions.ApiKeysHttpHeaderName,
                        QueryStringParameterName = authenticationOptions.ApiKeysQueryStringParameterName
                    });
                }
            }

            app.Use<CurrentUserOwinMiddleware>(container.Resolve<Func<ICurrentUser>>());
        }
Exemplo n.º 17
0
 public SecretRekeyProvider(IDialogCoordinator dialogCoordinator, ILogger <SecretRekeyProvider> logger, AuthenticationOptions authnOptions, EmailOptions emailOptions, IProtectedSecretProvider secretProvider)
 {
     this.dialogCoordinator = dialogCoordinator;
     this.logger            = logger;
     this.authnOptions      = authnOptions;
     this.emailOptions      = emailOptions;
     this.secretProvider    = secretProvider;
 }
Exemplo n.º 18
0
        public void Configuration(IAppBuilder app, string virtualRoot, string routPrefix)
        {
            VirtualRoot = virtualRoot;

            _assembliesPath = HostingEnvironment.MapPath(VirtualRoot + "/App_Data/Modules");
            var platformPath = HostingEnvironment.MapPath(VirtualRoot).EnsureEndSeparator();
            var modulesVirtualPath = VirtualRoot + "/Modules";
            var modulesPhysicalPath = HostingEnvironment.MapPath(modulesVirtualPath).EnsureEndSeparator();

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainOnAssemblyResolve;

            //Modules initialization
            var bootstrapper = new VirtoCommercePlatformWebBootstrapper(modulesVirtualPath, modulesPhysicalPath, _assembliesPath, platformPath);
            bootstrapper.Run();

            var container = bootstrapper.Container;
            container.RegisterInstance(app);

            var moduleInitializerOptions = (ModuleInitializerOptions)container.Resolve<IModuleInitializerOptions>();
            moduleInitializerOptions.VirtualRoot = virtualRoot;
            moduleInitializerOptions.RoutPrefix = routPrefix;

            //Initialize Platform dependencies
            const string connectionStringName = "VirtoCommerce";
            InitializePlatform(app, container, connectionStringName);

            var moduleManager = container.Resolve<IModuleManager>();
            var moduleCatalog = container.Resolve<IModuleCatalog>();


            var applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase.EnsureEndSeparator();

            // Register URL rewriter for platform scripts
            var scriptsPhysicalPath = HostingEnvironment.MapPath(VirtualRoot + "/Scripts").EnsureEndSeparator();
            var scriptsRelativePath = MakeRelativePath(applicationBase, scriptsPhysicalPath);
            var platformUrlRewriterOptions = new UrlRewriterOptions();
            platformUrlRewriterOptions.Items.Add(PathString.FromUriComponent("/$(Platform)/Scripts"), "");
            app.Use<UrlRewriterOwinMiddleware>(platformUrlRewriterOptions);
            app.UseStaticFiles(new StaticFileOptions
            {
                FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(scriptsRelativePath)
            });


        
            // Register URL rewriter before modules initialization
            if (Directory.Exists(modulesPhysicalPath))
            {
                var modulesRelativePath = MakeRelativePath(applicationBase, modulesPhysicalPath);

                var urlRewriterOptions = new UrlRewriterOptions();

                foreach (var module in moduleCatalog.Modules.OfType<ManifestModuleInfo>())
                {
                    var urlRewriteKey = string.Format(CultureInfo.InvariantCulture, "/Modules/$({0})", module.ModuleName);
                    var urlRewriteValue = MakeRelativePath(modulesPhysicalPath, module.FullPhysicalPath);
                    urlRewriterOptions.Items.Add(PathString.FromUriComponent(urlRewriteKey), "/" + urlRewriteValue);

                    moduleInitializerOptions.ModuleDirectories.Add(module.ModuleName, module.FullPhysicalPath);
                }

                app.Use<UrlRewriterOwinMiddleware>(urlRewriterOptions);
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(modulesRelativePath)
                });
            }

            // Ensure all modules are loaded
            foreach (var module in moduleCatalog.Modules.Where(x => x.State == ModuleState.NotStarted))
            {
                moduleManager.LoadModule(module.ModuleName);
            }

            // Post-initialize

            // Platform MVC configuration
            if (IsApplication)
            {
                AreaRegistration.RegisterAllAreas();
            }

            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();

            // Security OWIN configuration
            var authenticationOptions = new AuthenticationOptions
            {
                CookiesEnabled = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Cookies.Enabled", true),
                CookiesValidateInterval = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Cookies.ValidateInterval", TimeSpan.FromDays(1)),
                BearerTokensEnabled = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:BearerTokens.Enabled", true),
                BearerTokensExpireTimeSpan = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:BearerTokens.AccessTokenExpireTimeSpan", TimeSpan.FromHours(1)),
                HmacEnabled = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Hmac.Enabled", true),
                HmacSignatureValidityPeriod = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:Hmac.SignatureValidityPeriod", TimeSpan.FromMinutes(20)),
                ApiKeysEnabled = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:ApiKeys.Enabled", true),
                ApiKeysHttpHeaderName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:ApiKeys.HttpHeaderName", "api_key"),
                ApiKeysQueryStringParameterName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Authentication:ApiKeys.QueryStringParameterName", "api_key"),
            };
            OwinConfig.Configure(app, container, connectionStringName, authenticationOptions);

            RecurringJob.AddOrUpdate<SendNotificationsJobs>("SendNotificationsJob", x => x.Process(), "*/1 * * * *");

            var notificationManager = container.Resolve<INotificationManager>();
            notificationManager.RegisterNotificationType(() => new RegistrationEmailNotification(container.Resolve<IEmailNotificationSendingGateway>())
            {
                DisplayName = "Registration notification",
                Description = "This notification sends by email to client when he finish registration",
                NotificationTemplate = new NotificationTemplate
                {
                    Body = PlatformNotificationResource.RegistrationNotificationBody,
                    Subject = PlatformNotificationResource.RegistrationNotificationSubject,
                    Language = "en-US"
                }
            });

            notificationManager.RegisterNotificationType(() => new ResetPasswordEmailNotification(container.Resolve<IEmailNotificationSendingGateway>())
            {
                DisplayName = "Reset password notification",
                Description = "This notification sends by email to client when he want to reset his password",
                NotificationTemplate = new NotificationTemplate
                {
                    Body = PlatformNotificationResource.ResetPasswordNotificationBody,
                    Subject = PlatformNotificationResource.ResetPasswordNotificationSubject,
                    Language = "en-US"
                }
            });

            var postInitializeModules = moduleCatalog.CompleteListWithDependencies(moduleCatalog.Modules)
                .Where(m => m.ModuleInstance != null)
                .ToArray();

            foreach (var module in postInitializeModules)
            {
                moduleManager.PostInitializeModule(module);
            }

            // SignalR
            var tempCounterManager = new TempPerformanceCounterManager();
            GlobalHost.DependencyResolver.Register(typeof(IPerformanceCounterManager), () => tempCounterManager);
            var hubConfiguration = new HubConfiguration();
            hubConfiguration.EnableJavaScriptProxies = false;
            app.MapSignalR("/" + moduleInitializerOptions.RoutPrefix + "signalr", hubConfiguration);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Sets up authentication schemes.
 /// </summary>
 private void SetupAuthentication(AuthenticationOptions options)
 {
     options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
 }
Exemplo n.º 20
0
        public static void AddBearers
        (
            this IServiceCollection services,
            IWebHostEnvironment environment,
            OidcAuthorizationServerOptions openIdOptions,
            AuthenticationOptions authenticationOptions,
            string[] schemes
        )
        {
            services
            .AddDbContext <DbContext>(options =>
            {
                // Configure the context to use an in-memory store.
                options.UseInMemoryDatabase(nameof(DbContext));

                // Register the entity sets needed by OpenIddict.
                // Note: use the generic overload if you need
                // to replace the default OpenIddict entities.
                options.UseOpenIddict();
            })
            .AddOpenIddict()
            .AddCore(options =>
            {
                // Configure OpenIddict to use the Entity Framework Core stores and entities.
                options.UseEntityFrameworkCore().UseDbContext <DbContext>();
            })
            .AddServer(options =>
            {
                // Register the ASP.NET Core MVC binder used by OpenIddict.
                // Note: if you don't call this method, you won't be able to
                // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
                options.UseMvc();

                // Enable the authorization/token endpoints (required to use the code flow).
                options.EnableTokenEndpoint(@$ "/{authenticationOptions.TokenEndpoint
                            .Replace(authenticationOptions.Issuer, string.Empty)}");
                //.EnableAuthorizationEndpoint("/connect/authorize");

                // Allow client applications to use the grant_type=client_credentials flow.
                options.AllowClientCredentialsFlow();

                // During development, you can disable the HTTPS requirement.
                if (environment.IsDevelopment())
                {
                    options.DisableHttpsRequirement();
                }

                // Accept token requests that don't specify a client_id.
                // options.AcceptAnonymousClients();

                options.EnableRequestCaching();

                // Note: to use JWT access tokens instead of the default
                // encrypted format, the following lines are required:
                //
                options.UseJsonWebTokens();

                // Register a new ephemeral key, that is discarded when the application
                // shuts down. Tokens signed using this key are automatically invalidated.
                // This method should only be used during development.
                //options.AddEphemeralSigningKey();

                // On production, using a X.509 certificate stored in the machine store is recommended.
                options.AddSigningCertificate(LoadCertificate(openIdOptions));

                var expiryInSeconds = openIdOptions.AccessTokenExpiration;
                options.SetAccessTokenLifetime(TimeSpan.FromSeconds(Convert.ToDouble(expiryInSeconds)));

                // Note: if you don't want to use permissions, you can disable
                // permission enforcement by uncommenting the following lines:
                //
                // options.IgnoreEndpointPermissions()
                //        .IgnoreGrantTypePermissions()
                //        .IgnoreScopePermissions();
            });
Exemplo n.º 21
0
        public static void Configure(IAppBuilder app, IUnityContainer container, string databaseConnectionStringName, AuthenticationOptions authenticationOptions)
        {
            app.CreatePerOwinContext(() => container.Resolve<SecurityDbContext>());
            app.CreatePerOwinContext(() => container.Resolve<ApplicationUserManager>());

            if (authenticationOptions.CookiesEnabled)
            {
                // Enable the application to use a cookie to store information for the signed in user
                // and to use a cookie to temporarily store information about a user logging in with a third party login provider
                // Configure the sign in cookie
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                    //LoginPath = new PathString("/Account/Logon"),
                    Provider = new CookieAuthenticationProvider
                    {
                        // Enables the application to validate the security stamp when the user logs in.
                        // This is a security feature which is used when you change a password or add an external login to your account.  
                        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                            validateInterval: authenticationOptions.CookiesValidateInterval,
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                    }
                });
            }

            if (authenticationOptions.BearerTokensEnabled)
            {
                app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath = new PathString("/Token"),
                    AuthorizeEndpointPath = new PathString("/Account/Authorize"),
                    Provider = new ApplicationOAuthProvider(PublicClientId),
                    AccessTokenExpireTimeSpan = authenticationOptions.BearerTokensExpireTimeSpan,
                    AllowInsecureHttp = true
                });
            }

            if (authenticationOptions.HmacEnabled || authenticationOptions.ApiKeysEnabled)
            {
                var apiAccountProvider = container.Resolve<IApiAccountProvider>();
                var claimsIdentityProvider = container.Resolve<IClaimsIdentityProvider>();
                var cacheManager = container.Resolve<CacheManager>();

                var cacheSettings = new[]
                {
                    new CacheSettings(HmacAuthenticationHandler.CacheGroup, TimeSpan.FromSeconds(60))
                };
                cacheManager.AddCacheSettings(cacheSettings);

                if (authenticationOptions.HmacEnabled)
                {
                    app.UseHmacAuthentication(new HmacAuthenticationOptions
                    {
                        ApiCredentialsProvider = apiAccountProvider,
                        IdentityProvider = claimsIdentityProvider,
                        CacheManager = cacheManager,
                        SignatureValidityPeriod = authenticationOptions.HmacSignatureValidityPeriod
                    });
                }

                if (authenticationOptions.ApiKeysEnabled)
                {
                    app.UseApiKeysAuthentication(new ApiKeysAuthenticationOptions
                    {
                        ApiCredentialsProvider = apiAccountProvider,
                        IdentityProvider = claimsIdentityProvider,
                        CacheManager = cacheManager,
                        HttpHeaderName = authenticationOptions.ApiKeysHttpHeaderName,
                        QueryStringParameterName = authenticationOptions.ApiKeysQueryStringParameterName
                    });
                }
            }

            var permissionService = container.Resolve<IPermissionService>();
            app.UseHangfire(config =>
            {
                config.UseUnityActivator(container);
                config.UseSqlServerStorage(databaseConnectionStringName, new SqlServerStorageOptions { PrepareSchemaIfNecessary = false, QueuePollInterval = TimeSpan.FromSeconds(60) /* 15 Default value */ });
                config.UseAuthorizationFilters(new PermissionBasedAuthorizationFilter(permissionService) { Permission = PredefinedPermissions.BackgroundJobsManage });
                config.UseServer();
            });
        }
Exemplo n.º 22
0
 public AuthDialog(IAuthProvider AuthProvider, AuthenticationOptions AuthOptions, string Prompt = "Please click to sign in: ")
 {
     this.prompt       = Prompt;
     this.authProvider = AuthProvider;
     this.authOptions  = AuthOptions;
 }
Exemplo n.º 23
0
 public DownstreamReRouteBuilder WithAuthenticationOptions(AuthenticationOptions authenticationOptions)
 {
     _authenticationOptions = authenticationOptions;
     return(this);
 }
 private void WhenICreateTheAuthenticationOptions()
 {
     _result = _authOptionsCreator.Create(_fileReRoute);
 }
 public AuthenticationController(ILogger logger, IUserService userService, CoreSettings settings, IExternalClaimsFilter externalClaimsFilter, AuthenticationOptions authenticationOptions, InternalConfiguration internalConfiguration)
 {
     this.logger                = logger;
     this.userService           = userService;
     this.settings              = settings;
     this.externalClaimsFilter  = externalClaimsFilter;
     this.authenticationOptions = authenticationOptions;
     this.internalConfiguration = internalConfiguration;
 }
 private void SetAuthenticationOptions(AuthenticationOptions options)
 {
     options.DefaultScheme          = Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme = Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectDefaults.AuthenticationScheme;
 }
Exemplo n.º 27
0
 /// <inheritdoc />
 public abstract IWorkItemStore Create(AuthenticationOptions options);
Exemplo n.º 28
0
        public static KrbAsReq CreateAsReq(KerberosCredential credential, AuthenticationOptions options)
        {
            var kdcOptions = (KdcOptions)(options & ~AuthenticationOptions.AllAuthentication);

            var hostAddress = Environment.MachineName;

            var padata = new List <KrbPaData>()
            {
                new KrbPaData
                {
                    Type  = PaDataType.PA_PAC_REQUEST,
                    Value = new KrbPaPacRequest
                    {
                        IncludePac = options.HasFlag(AuthenticationOptions.IncludePacRequest)
                    }.Encode().AsMemory()
                }
            };

            if (options.HasFlag(AuthenticationOptions.PreAuthenticate))
            {
                KerberosConstants.Now(out DateTimeOffset timestamp, out int usec);

                var ts = new KrbPaEncTsEnc
                {
                    PaTimestamp = timestamp,
                    PaUSec      = usec
                };

                var tsEncoded = ts.Encode().AsMemory();

                KrbEncryptedData encData = KrbEncryptedData.Encrypt(
                    tsEncoded,
                    credential.CreateKey(),
                    KeyUsage.PaEncTs
                    );

                padata.Add(new KrbPaData
                {
                    Type  = PaDataType.PA_ENC_TIMESTAMP,
                    Value = encData.Encode().AsMemory()
                });
            }

            var asreq = new KrbAsReq()
            {
                MessageType = MessageType.KRB_AS_REQ,
                Body        = new KrbKdcReqBody
                {
                    Addresses = new[] {
                        new KrbHostAddress {
                            AddressType = AddressType.NetBios,
                            Address     = Encoding.ASCII.GetBytes(hostAddress.PadRight(16, ' '))
                        }
                    },
                    CName = new KrbPrincipalName
                    {
                        Name = new[] { $"{credential.UserName}@{credential.Domain}" },
                        Type = PrincipalNameType.NT_ENTERPRISE
                    },
                    EType      = KerberosConstants.ETypes.ToArray(),
                    KdcOptions = kdcOptions,
                    Nonce      = KerberosConstants.GetNonce(),
                    RTime      = KerberosConstants.EndOfTime,
                    Realm      = credential.Domain,
                    SName      = new KrbPrincipalName
                    {
                        Type = PrincipalNameType.NT_SRV_INST,
                        Name = new[] { "krbtgt", credential.Domain }
                    },
                    Till = KerberosConstants.EndOfTime
                },
                PaData = padata.ToArray()
            };

            return(asreq);
        }
 public static void SetSignInChallengeResultCallback(
     this AuthenticationOptions authOptions,
     Func <IOwinContext, AuthenticationProperties> authProperties)
 {
     authOptions.Description.Properties["ChallengeResultCallback"] = authProperties;
 }
Exemplo n.º 30
0
 private void ConfigureAuthenticationOptions(AuthenticationOptions options)
 {
     options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
 }
 /// <summary>
 /// Used during the External authentication process to assign external sign-in options
 /// that are used by the Umbraco authentication process.
 /// </summary>
 /// <param name="authOptions"></param>
 /// <param name="options"></param>
 public static void SetExternalSignInAutoLinkOptions(
     this AuthenticationOptions authOptions,
     ExternalSignInAutoLinkOptions options)
 {
     authOptions.Description.Properties["ExternalSignInAutoLinkOptions"] = options;
 }
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">IServiceCollection instance.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            // Add all options set from configuration values.
            services.AddOptions <AuthenticationOptions>()
            .Configure <IConfiguration>((authenticationOptions, configuration) =>
            {
                Startup.FillAuthenticationOptionsProperties(authenticationOptions, configuration);
            });
            services.AddOptions <BotOptions>()
            .Configure <IConfiguration>((botOptions, configuration) =>
            {
                botOptions.UserAppId         = configuration.GetValue <string>("UserAppId");
                botOptions.UserAppPassword   = configuration.GetValue <string>("UserAppPassword");
                botOptions.AuthorAppId       = configuration.GetValue <string>("AuthorAppId");
                botOptions.AuthorAppPassword = configuration.GetValue <string>("AuthorAppPassword");
            });
            services.AddOptions <BotFilterMiddlewareOptions>()
            .Configure <IConfiguration>((botFilterMiddlewareOptions, configuration) =>
            {
                botFilterMiddlewareOptions.DisableTenantFilter =
                    configuration.GetValue <bool>("DisableTenantFilter", false);
                botFilterMiddlewareOptions.AllowedTenants =
                    configuration.GetValue <string>("AllowedTenants");
            });
            services.AddOptions <RepositoryOptions>()
            .Configure <IConfiguration>((repositoryOptions, configuration) =>
            {
                repositoryOptions.StorageAccountConnectionString =
                    configuration.GetValue <string>("StorageAccountConnectionString");

                // Setting this to true because the main application should ensure that all
                // tables exist.
                repositoryOptions.EnsureTableExists = true;
            });
            services.AddOptions <MessageQueueOptions>()
            .Configure <IConfiguration>((messageQueueOptions, configuration) =>
            {
                messageQueueOptions.ServiceBusConnection =
                    configuration.GetValue <string>("ServiceBusConnection");
            });
            services.AddOptions <DataQueueMessageOptions>()
            .Configure <IConfiguration>((dataQueueMessageOptions, configuration) =>
            {
                dataQueueMessageOptions.ForceCompleteMessageDelayInSeconds =
                    configuration.GetValue <double>("ForceCompleteMessageDelayInSeconds", 86400);
            });

            services.AddOptions <UserAppOptions>()
            .Configure <IConfiguration>((options, configuration) =>
            {
                options.ProactivelyInstallUserApp =
                    configuration.GetValue <bool>("ProactivelyInstallUserApp", true);

                options.UserAppExternalId =
                    configuration.GetValue <string>("UserAppExternalId", "148a66bb-e83d-425a-927d-09f4299a9274");
            });

            services.AddOptions();

            // Add localization services.
            services.AddLocalizationSettings(this.Configuration);

            // Add authentication services.
            AuthenticationOptions authenticationOptionsParameter = new AuthenticationOptions();

            Startup.FillAuthenticationOptionsProperties(authenticationOptionsParameter, this.Configuration);
            services.AddAuthentication(this.Configuration, authenticationOptionsParameter);
            services.AddControllersWithViews();

            // Setup SPA static files.
            // In production, the React files will be served from this directory.
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });

            // Add blob client.
            services.AddSingleton(sp => new BlobContainerClient(
                                      sp.GetService <IConfiguration>().GetValue <string>("StorageAccountConnectionString"),
                                      Common.Constants.BlobContainerName));

            // The bot needs an HttpClient to download and upload files.
            services.AddHttpClient();

            // Add bot services.
            services.AddTransient <TeamsDataCapture>();
            services.AddTransient <TeamsFileUpload>();
            services.AddTransient <UserTeamsActivityHandler>();
            services.AddTransient <AuthorTeamsActivityHandler>();
            services.AddSingleton <ICredentialProvider, ConfigurationCredentialProvider>();
            services.AddTransient <CompanyCommunicatorBotFilterMiddleware>();
            services.AddSingleton <CompanyCommunicatorBotAdapter>();
            services.AddSingleton <BotFrameworkHttpAdapter>();

            // Add repositories.
            services.AddSingleton <ITeamDataRepository, TeamDataRepository>();
            services.AddSingleton <IUserDataRepository, UserDataRepository>();
            services.AddSingleton <ISentNotificationDataRepository, SentNotificationDataRepository>();
            services.AddSingleton <INotificationDataRepository, NotificationDataRepository>();
            services.AddSingleton <IExportDataRepository, ExportDataRepository>();
            services.AddSingleton <IAppConfigRepository, AppConfigRepository>();
            services.AddSingleton <IUrlTrackingDataRepository, UrlTrackingDataRepository>();

            // Add service bus message queues.
            services.AddSingleton <IPrepareToSendQueue, PrepareToSendQueue>();
            services.AddSingleton <IDataQueue, DataQueue>();
            services.AddSingleton <IExportQueue, ExportQueue>();

            // Add draft notification preview services.
            services.AddTransient <DraftNotificationPreviewService>();

            // Add microsoft graph services.
            services.AddScoped <IAuthenticationProvider, GraphTokenProvider>();
            services.AddScoped <IGraphServiceClient, GraphServiceClient>();
            services.AddScoped <Beta.IGraphServiceClient, Beta.GraphServiceClient>();
            services.AddScoped <IGraphServiceFactory, GraphServiceFactory>();
            services.AddScoped <IGroupsService>(sp => sp.GetRequiredService <IGraphServiceFactory>().GetGroupsService());
            services.AddScoped <IAppCatalogService>(sp => sp.GetRequiredService <IGraphServiceFactory>().GetAppCatalogService());

            // Add Application Insights telemetry.
            services.AddApplicationInsightsTelemetry();

            // Add miscellaneous dependencies.
            services.AddTransient <TableRowKeyGenerator>();
            services.AddTransient <AdaptiveCardCreator>();
            services.AddTransient <IAppSettingsService, AppSettingsService>();
            services.AddTransient <IUserDataService, UserDataService>();
            services.AddTransient <ITeamMembersService, TeamMembersService>();

            // Enable redirect controller
            services.AddHttpContextAccessor();
        }
Exemplo n.º 33
0
        public static void Register(HttpConfiguration config)
        {
            var authConfig = new AuthenticationConfiguration
            {
                RequireSsl = false,
                ClaimsAuthenticationManager = new ClaimsTransformer(),
                EnableSessionToken          = true,
            };
            var registry = new ConfigurationBasedIssuerNameRegistry();

            registry.AddTrustedIssuer(System.Configuration.ConfigurationManager.AppSettings["SigningThumbPrint"], System.Configuration.ConfigurationManager.AppSettings["IssuerURI"]);
            var handlerConfig = new SecurityTokenHandlerConfiguration();

            handlerConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(System.Configuration.ConfigurationManager.AppSettings["AudianceUri"]));
            handlerConfig.IssuerNameRegistry   = registry;
            handlerConfig.CertificateValidator = X509CertificateValidator.None;
            handlerConfig.ServiceTokenResolver = new X509CertificateStoreTokenResolver(StoreName.My, StoreLocation.LocalMachine);
            authConfig.AddSaml2(handlerConfig, AuthenticationOptions.ForAuthorizationHeader("SAML"), AuthenticationScheme.SchemeOnly("SAML"));

            config.MessageHandlers.Add(new AuthenticationHandler(authConfig));

            config.Routes.MapHttpRoute(
                name: "UsersCurrentPermittedUser",
                routeTemplate: "api/Users/{logonUserName}/CurrentPermittedUser",
                defaults: new { Controller = "UsersCurrentPermittedUser", id = RouteParameter.Optional });
            //constraints:new {httpMethod = new System.Web.Http.Routing.HttpMethodConstraint(HttpMethod.Get,HttpMethod.Post)});


            config.Routes.MapHttpRoute(
                name: "Calculations",
                routeTemplate: "api/Periods/{PeriodId}/Calculations/{id}",
                defaults: new { Controller = "Calculations", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "CalculationsState",
                routeTemplate: "api/Periods/{PeriodId}/Calculations/{id}/State",
                defaults: new { Controller = "CalculationsState", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "CalculationsExceptions",
                routeTemplate: "api/Periods/{PeriodId}/Calculations/{calculationId}/Exceptions/{id}",
                defaults: new { Controller = "CalculationsExceptions", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "JobIndexPoints",
                routeTemplate: "api/Periods/{PeriodId}/Calculations/{CalculationId}/JobIndexpoints/{id}",
                defaults: new { Controller = "JobIndexPoints", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "JobCustomFields",
                routeTemplate: "api/Jobs/{jobId}/CustomFields/{id}",
                defaults: new { Controller = "JobCustomFields", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "PeriodState",
                routeTemplate: "api/Periods/{id}/State",
                defaults: new { Controller = "PeriodsState", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "PeriodSourceDestinationState",
                routeTemplate: "api/SourcePeriods/{sourcePeriodId}/DestinationPeriods/{destinationPeriodId}/State",
                defaults: new { Controller = "PeriodSourceDestinationState", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "PolicyFunctions",
                routeTemplate: "api/Policies/{PolicyId}/Functions/{id}",
                defaults: new { Controller = "PolicyFunctions", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "PolicyRules",
                routeTemplate: "api/Policies/{PolicyId}/Rules/{id}",
                defaults: new { Controller = "PolicyRules", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "PolicyRuleTrails",
                routeTemplate: "api/Policies/{policyId}/Rules/{ruleId}/Trails/{id}",
                defaults: new { Controller = "PolicyRuleTrails", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "PolicyRuleCompilations",
                routeTemplate: "api/Policies/{PolicyId}/RuleCompilations/{id}",
                defaults: new { Controller = "RuleCompilations", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "PeriodUnits",
                routeTemplate: "api/Periods/{PeriodId}/Units/{id}",
                defaults: new { Controller = "PeriodUnits", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "UnitInquirySubjectsController",
                routeTemplate: "api/Periods/{PeriodId}/Units/{UnitId}/InquirySubjects",
                defaults: new { Controller = "UnitInquirySubjects", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "UnitVerifiersController",
                routeTemplate: "api/Periods/{PeriodId}/Units/{UnitId}/Verifiers",
                defaults: new { Controller = "UnitVerifiers", id = RouteParameter.Optional });


            config.Routes.MapHttpRoute(
                name: "InquirerInquiryUnits",
                routeTemplate: "api/Periods/{PeriodId}/Inquirers/{InquirerEmployeeNo}/InquiryUnits",
                defaults: new { Controller = "InquirerInquiryUnits", id = RouteParameter.Optional });


            config.Routes.MapHttpRoute(
                name: "EmployeeUnits",
                routeTemplate: "api/Periods/{PeriodId}/Employees/{EmployeeNo}/Units",
                defaults: new { Controller = "EmployeeUnits", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "InquiryUnitInquiryUnitIndexPoints",
                routeTemplate:
                "api/Periods/{PeriodId}/Inquirers/{InquirerEmployeeNo}/Units/{unitId}/InquiryUnitIndexPoints",
                defaults: new { Controller = "InquiryUnitInquiryUnitIndexPoints", id = RouteParameter.Optional });



            config.Routes.MapHttpRoute(
                name: "PeriodEmployees",
                routeTemplate: "api/Periods/{PeriodId}/Employees/{id}",
                defaults: new { Controller = "PeriodEmployees", id = RouteParameter.Optional });



            config.Routes.MapHttpRoute(
                name: "EmployeeJobPositions",
                routeTemplate: "api/Periods/{PeriodId}/Employees/{EmployeeNo}/JobPositions",
                defaults: new { Controller = "EmployeeJobPositions", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "PeriodJobPositions",
                routeTemplate: "api/Periods/{PeriodId}/JobPositions/{id}",
                defaults: new { Controller = "PeriodJobPositions", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "PeriodJobIndex",
                routeTemplate: "api/Periods/{PeriodId}/JobIndices/{id}",
                defaults: new { Controller = "PeriodJobIndex", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "PeriodUnitIndex",
                routeTemplate: "api/Periods/{PeriodId}/UnitIndices/{id}",
                defaults: new { Controller = "PeriodUnitIndex", id = RouteParameter.Optional });


            config.Routes.MapHttpRoute(
                name: "PeriodJobs",
                routeTemplate: "api/Periods/{PeriodId}/Jobs/{id}",
                defaults: new { Controller = "PeriodJobs", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "JobIndexCustomFields",
                routeTemplate: "api/JobIndices/{jobindexid}/CustomFields/{id}",
                defaults: new { Controller = "CustomFields", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "JobPositionJobs",
                routeTemplate: "api/Periods/{PeriodId}/JobPositions/{JobPositionId}/Jobs",
                defaults: new { Controller = "JobPositionJobs", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "JobPositionInquirySubjects",
                routeTemplate: "api/Periods/{PeriodId}/JobPositions/{JobPositionId}/InquirySubjects",
                defaults: new { Controller = "JobPositionInquirySubjects", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "InquirySubjectInquirers",
                routeTemplate: "api/Periods/{PeriodId}/JobPositions/{JobPositionId}/InquirySubjects/{InquirySubjectEmployeeNo}/Inquirers",
                defaults: new { Controller = "InquirySubjectInquirers", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "InquirerInquirySubjects",
                routeTemplate: "api/Periods/{PeriodId}/Inquirers/{InquirerEmployeeNo}/InquirySubjects",
                defaults: new { Controller = "InquirerInquirySubjects", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "InquirerInquiryIndices",
                routeTemplate: "api/Periods/{PeriodId}/Inquirers/{InquirerEmployeeNo}/InquiryIndices",
                defaults: new { Controller = "InquirerInquiryIndices", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "InquirySubjectJobPositionInquiryJobIndexPoints",
                routeTemplate:
                "api/Periods/{PeriodId}/Inquirers/{InquirerEmployeeNo}/InquirySubjects/{InquirySubjectEmployeeNo}/JobPositions/{JobPositionId}/InquiryJobIndexPoints",
                defaults: new { Controller = "InquirySubjectJobPositionInquiryJobIndexPoints", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "InquiryIndexInquiryJobIndexPoints",
                routeTemplate:
                "api/Periods/{PeriodId}/Inquirers/{InquirerEmployeeNo}/InquiryIndices/{jobIndexId}/InquiryJobIndexPoints",
                defaults: new { Controller = "InquiryIndexInquiryJobIndexPoints", id = RouteParameter.Optional });


            config.Routes.MapHttpRoute(
                name: "PeriodClaims",
                routeTemplate: "api/Periods/{PeriodId}/Claims/{id}",
                defaults: new { Controller = "PeriodClaims", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "PeriodClaimStates",
                routeTemplate: "api/Periods/{PeriodId}/ClaimStates",
                defaults: new { Controller = "PeriodClaimStates", id = RouteParameter.Optional });
            config.Routes.MapHttpRoute(
                name: "PeriodClaimTypes",
                routeTemplate: "api/Periods/{PeriodId}/ClaimTypes",
                defaults: new { Controller = "PeriodClaimTypes", id = RouteParameter.Optional });

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            config.Formatters.Add(new PlainTextFormatter());
            config.Filters.Add(new GlobalExceptionFilterAttribute());
            config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling       = TypeNameHandling.Auto;
            config.Formatters.JsonFormatter.SerializerSettings.TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;
            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
                = ReferenceLoopHandling.Serialize;
            config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling
                = PreserveReferencesHandling.Objects;
            config.Services.RemoveAll(typeof(System.Web.Http.Validation.ModelValidatorProvider), v => v is InvalidModelValidatorProvider);
        }
Exemplo n.º 34
0
 private void JwtBearerDefault(AuthenticationOptions obj)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 35
0
 public static void ConfigureAuthenticationOptions(this AuthenticationOptions authenticationOptions)
 {
     authenticationOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
     authenticationOptions.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
 }