示例#1
0
        public GraphAuthProvider(IMemoryCache memoryCache, IConfiguration configuration)
        {
            var azureOptions = new AzureAdOptions();

            configuration.Bind("AzureAd", azureOptions);

            _appId       = azureOptions.ClientId;
            _credential  = new ClientCredential(azureOptions.ClientSecret);
            _scopes      = azureOptions.GraphScopes.Split(new[] { ' ' });
            _redirectUri = azureOptions.BaseUrl + azureOptions.CallbackPath;

            _memoryCache = memoryCache;
        }
        private async Task <Room> GetRoomData(Room room, DateTime dt, string tenantId)
        {
            var identifier = User.FindFirst(Startup.ObjectIdentifierType)?.Value;

            var azureOptions = new AzureAdOptions();

            _configuration.Bind("AzureAd", azureOptions);

            if (room.HasMailBox)
            {
                Graph::GraphServiceClient graphClient = GetGraphServiceClient(new[] { "Calendars.Read.Shared" }, tenantId);
                room = await GraphService.GetRoomAvailability(graphClient, room, HttpContext, dt);
            }

            if (_tenantConfig.bGridConfig.bGridUser != "")
            {
                var roomOccupancies = await GetbGridOccupancies();

                var roomTemperatures = await GetbGridTemperatures();

                if (room.Nodes != null)
                {
                    var roomNodes = roomOccupancies.Where(r => room.Nodes.Where(ro => ro.Id == r.location_id.ToString()).Count() > 0);
                    if (roomNodes != null)
                    {
                        var occupiedNodes = roomNodes.Where(nodes => nodes.value == 2);
                        room.Occupied = occupiedNodes == null ? -1 : occupiedNodes.Count() > 0 ? 2 : 0;

                        //Get Associated Island
                        //var islands = _bGridIslands.Where(i => i.locations.Any(l => room.Nodes.Any(n => Convert.ToInt32(n.Id).Equals(l))));
                        //if(islands != null)
                        //{
                        //    room.Island = islands.First();
                        //}
                    }

                    var roomNodesTemp = roomTemperatures.Where(r => room.Nodes.Where(ro => ro.Id == r.location_id.ToString()).Count() > 0);
                    if (roomNodesTemp != null)
                    {
                        var roomNodesTempLatest = roomNodesTemp.GroupBy(r => r.location_id).Select(ro => ro.OrderByDescending(x => x.timestamp).FirstOrDefault());
                        if (roomNodesTemp.Count() > 0)
                        {
                            var avgTemp = roomNodesTemp.Average(r => Convert.ToDecimal(r.value));
                            room.Temperature = avgTemp;
                        }
                    }
                }
            }

            return(room);
        }
        public ACRService(IOptions <AzureAdOptions> azureAdOptionsValue, ILogger <ACRService> logger)
        {
            this.logger    = logger;
            azureAdOptions = azureAdOptionsValue.Value;

            var credentials = SdkContext.AzureCredentialsFactory
                              .FromServicePrincipal(azureAdOptions.ClientId, azureAdOptions.ClientSecret,
                                                    azureAdOptions.TenantId, AzureEnvironment.AzureGlobalCloud);

            azure = Microsoft.Azure.Management.Fluent.Azure
                    .Configure()
                    .Authenticate(credentials)
                    .WithSubscription(azureAdOptions.SubscriptionId);
        }
        public GraphAuthProvider(IConfiguration configuration)
        {
            var azureOptions = new AzureAdOptions();

            configuration.Bind("AzureAd", azureOptions);

            _app = ConfidentialClientApplicationBuilder.Create(azureOptions.ClientId)
                   .WithClientSecret(azureOptions.ClientSecret)
                   .WithAuthority(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount)
                   .WithRedirectUri(azureOptions.BaseUrl + azureOptions.CallbackPath)
                   .Build();

            _scopes = azureOptions.GraphScopes.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        }
示例#5
0
        public GraphAuthProvider(IMemoryCache memoryCache, IConfiguration configuration, IHttpContextAccessor contextAccessor)
        {
            var azureOptions = new AzureAdOptions();

            configuration.Bind("AzureAd", azureOptions);

            this.appId           = azureOptions.ClientId;
            this.credential      = new ClientCredential(azureOptions.ClientSecret);
            this.scopes          = azureOptions.GraphScopes.Split(new[] { ' ' });
            this.redirectUri     = azureOptions.BaseUrl + azureOptions.CallbackPath;
            this.secret          = azureOptions.ClientSecret;
            this.memoryCache     = memoryCache;
            this.contextAccessor = contextAccessor;
        }
示例#6
0
        public GraphAuthProvider(IConfiguration configuration)
        {
            _azureOptions = new AzureAdOptions();
            configuration.Bind("AzureAd", _azureOptions);

            _app = ConfidentialClientApplicationBuilder.Create(_azureOptions.ClientId)
                   .WithClientSecret(_azureOptions.ClientSecret)
                   .WithAuthority(new Uri(_azureOptions.Authority))
                   .Build();

            Authority = _app.Authority;

            _scopes = new string[] { $"{_azureOptions.ApiUrl}.default" };
        }
示例#7
0
        private static void SetAzureADOptions()
        {
            var azureOptions = new AzureAdOptions();

            configuration.Bind("GraphAzureAD", azureOptions);

            clientId         = azureOptions.ClientId;
            clientSecret     = azureOptions.ClientSecret;
            tenantId         = azureOptions.Tenant;
            aadInstance      = azureOptions.Instance;
            graphResource    = azureOptions.GraphResource;
            graphAPIEndpoint = $"{azureOptions.GraphResource}{azureOptions.GraphResourceEndPoint}";
            authority        = $"{aadInstance}{tenantId}";
        }
示例#8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var azureOptions = new AzureAdOptions();

            Configuration.Bind("AzureAd", azureOptions);

            var saaSWebApiOptions = new Iconfiguration();

            Configuration.Bind("SaaSWebApi", saaSWebApiOptions);

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddOptions();

            // Token acquisition service based on MSAL.NET
            // and chosen token cache implementation
            services.AddMicrosoftIdentityPlatformAuthentication(Configuration)
            .AddMsal(Configuration, $"{azureOptions.GraphScopes}".Split(new[] { ' ' }))
            .AddInMemoryTokenCaches();

            // Add Graph
            services.AddApiService(Configuration);

            services.AddControllersWithViews(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();

                options.Filters.Add(new AuthorizeFilter(policy));
                options.Filters.Add(new AuthExceptionFilter());
            });

            services.AddAuthorization(option =>
            {
                option.AddPolicy("ISVAdmin", policy => policy.Requirements.Add(new ISVAdminRequirement("ISVAdmin")));
            });

            services.AddSingleton <IAuthorizationHandler, ISVAdminHandler>();

            services.AddHttpClient();
            services.AddTransient <ISubscriptionService, SubscriptionService>();
            services.AddRazorPages();
        }
示例#9
0
        public override async Task <AuthenticationResult> TokenForCurrentUser(string[] scopes)
        {
            if (accessor.HttpContext.Request.Headers.TryGetValue("Authorization",
                                                                 out Microsoft.Extensions.Primitives.StringValues value))
            {
                var token = value.FirstOrDefault();

                AzureAdOptions o = options.Value;

                IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId: o.ClientId)
                                                     .WithClientSecret(o.ClientSecret)
                                                     .WithTenantId(o.TenantId)
                                                     .Build();

                AuthenticationResult t =
                    await app.AcquireTokenOnBehalfOf(scopes, new UserAssertion(token.Split(" ")[1])).ExecuteAsync();

                return(t);
            }
            else
            {
                ClaimsPrincipal user = accessor.HttpContext.User;
                if (user == null || !user.Identity.IsAuthenticated)
                {
                    throw new ForbiddenException("Not authenticated");
                }

                try
                {
                    AuthenticationResult result = await tokenService.GetAccessTokenAsync(user, scopes);

                    return(result);
                }
                catch (MsalUiRequiredException e)
                {
                    if (e.Classification == UiRequiredExceptionClassification.ConsentRequired)
                    {
                        var message =
                            $"Consent missing: The app does not yet have your consent to the scope '{scopes[0]}'." +
                            $" Please first allow the app to act on your behalf, then try again." +
                            $" Scopes can be granted under the account settings.";
                        logger.LogError("Missing consent {@scopes}", scopes);
                        throw new MissingConsentException(message, scopes[0]);
                    }

                    throw;
                }
            }
        }
示例#10
0
        public GraphAuthProvider(IConfiguration configuration)
        {
            var azureOptions = new AzureAdOptions();

            configuration.Bind("AzureAd", azureOptions);

            // More info about MSAL Client Applications: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Client-Applications
            _app = ConfidentialClientApplicationBuilder.Create(azureOptions.ClientId)
                   .WithClientSecret(azureOptions.ClientSecret)
                   .WithAuthority(AzureCloudInstance.AzurePublic, AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount)
                   .WithRedirectUri(azureOptions.BaseUrl + azureOptions.CallbackPath)
                   .Build();

            _scopes = azureOptions.GraphScopes.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        }
示例#11
0
 public ServicePrincipalController(
     TokenService tokenService,
     GraphService graphService,
     IOptions <AzureAdOptions> adOptions,
     IOptions <OpenIdConnectOptions> oidcOptions,
     AzureManagementService azureManagementService,
     ServicePrincipalRepository repository)
 {
     _tokenService           = tokenService;
     _graphService           = graphService;
     _adOptions              = adOptions.Value;
     _oidcOptions            = oidcOptions.Value;
     _azureManagementService = azureManagementService;
     _repository             = repository;
 }
示例#12
0
        public override async Task <string> AccessTokenForApp()
        {
            AzureAdOptions o = options.Value;

            IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId: o.ClientId)
                                                 .WithClientSecret(o.ClientSecret)
                                                 .WithTenantId(o.TenantId)
                                                 .Build();

            var scopes = new string[] { "https://graph.microsoft.com/.default" };

            AuthenticationResult token = await app.AcquireTokenForClient(scopes).ExecuteAsync();

            return(token.AccessToken);
        }
        public override void Configure(IServiceCollection services)
        {
            AzureAdOptions azureAdOptions = new AzureAdOptions();

            Configuration.Bind("AzureAd", azureAdOptions);

            if (HostingEnvironment.IsDevelopment())
            {
                services.AddAuthorization();

                services.AddSingleton <IAuthorizationHelper, LocalDevelopmentAuthorizationHelper>();

                services.AddSingleton <IAuthorizationHandler, AlwaysAllowedForFundingStreamPermissionHandler>();
                services.AddSingleton <IAuthorizationHandler, AlwaysAllowedForSpecificationPermissionHandler>();

                services.AddMvc();
            }
            else
            {
                services.AddAuthentication(opts =>
                {
                    opts.DefaultAuthenticateScheme = AzureAuthenticationDefaults.AuthenticationScheme;
                    opts.DefaultChallengeScheme    = AzureAuthenticationDefaults.AuthenticationScheme;
                })
                .AddAzureAuthentication();

                services.AddAuthorization();

                services.AddSingleton <IAuthorizationHandler, FundingStreamPermissionHandler>();
                services.AddSingleton <IAuthorizationHandler, SpecificationPermissionHandler>();

                services.Configure <PermissionOptions>(options =>
                {
                    Configuration.GetSection("permissionOptions").Bind(options);
                });

                services.AddSingleton <IAuthorizationHelper, AuthorizationHelper>();

                services.AddMvc(config =>
                {
                    AuthorizationPolicy policy = new AuthorizationPolicyBuilder()
                                                 .RequireAuthenticatedUser()
                                                 .RequireClaim("groups", azureAdOptions.Groups?.Split(","))
                                                 .Build();
                    config.Filters.Add(new AuthorizeFilter(policy));
                });
            }
        }
示例#14
0
 public MageSignService(IOptions <AzureAdOptions> aadOptions,
                        IHostingEnvironment hostingEnvironment,
                        IKeyVaultService keyVaultService,
                        IServiceProvider serviceProvider,
                        ILogger <MageSignService> logger,
                        ITelemetryLogger telemetryLogger)
 {
     this.aadOptions      = aadOptions.Value;
     this.keyVaultService = keyVaultService;
     this.logger          = logger;
     this.telemetryLogger = telemetryLogger;
     magetoolPath         = Path.Combine(hostingEnvironment.ContentRootPath, "tools\\SDK\\mage.exe");
     signToolName         = Path.GetFileName(magetoolPath);
     // Need to delay this as it'd create a dependency loop if directly in the ctor
     signToolAggregate = new Lazy <ISigningToolAggregate>(() => serviceProvider.GetService <ISigningToolAggregate>());
 }
示例#15
0
        public void ConfigureDevelopmentServices(IServiceCollection services)
        {
            services.AddAuthorization(options => {
                options.DefaultPolicy = new AuthorizationPolicyBuilder()
                                        .RequireAssertion(_ => true)
                                        .Build();
            });

            System.Diagnostics.Trace.WriteLine("Configuring services in Development");
            AzureAdOptions opts = new AzureAdOptions();

            Configuration.Bind("AzureAd", opts);
            AzureAdOptions.Settings = opts;

            services.AddMvc();
        }
示例#16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <AzureAdOptions>(options => Configuration.Bind("AzureAd", options));
            ServiceProvider serviceProvider = services.BuildServiceProvider();
            AzureAdOptions  azureAdOptions  = serviceProvider.GetRequiredService <IOptions <AzureAdOptions> >().Value;

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Audience  = azureAdOptions.Audience;
                options.Authority = azureAdOptions.Authority;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false
                };
            });

            services.AddMvc(config =>
            {
                // Adding ADAL authentication
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSwaggerGen(c =>
            {
                //The generated Swagger JSON file will have these properties.
                c.SwaggerDoc("v1", new Info
                {
                    Title   = "SmartHotel.Services.FacilityManagement",
                    Version = "v1",
                });

                //Locate the XML file being generated by ASP.NET...
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

                //... and tell Swagger to use those XML comments.
                c.IncludeXmlComments(xmlPath);
            });
            services.AddCors();
            services.AddHttpClient();
            services.AddScoped <ITopologyClient, TopologyClient>();
        }
        public GraphAuthProvider(IMemoryCache memoryCache, IConfiguration configuration)
        {
            var azureOptions = new AzureAdOptions();

            configuration.Bind("AzureAd", azureOptions);

            _appId           = azureOptions.ClientId;
            _aadInstance     = azureOptions.Instance;
            _appSecret       = azureOptions.ClientSecret;
            _credential      = new Microsoft.Identity.Client.ClientCredential(azureOptions.ClientSecret); // For development mode purposes only. Production apps should use a client certificate.
            _scopes          = azureOptions.GraphScopes.Split(new[] { ' ' });
            _redirectUri     = azureOptions.BaseUrl + azureOptions.CallbackPath;
            _graphResourceId = azureOptions.GraphResourceId;
            _tenantId        = azureOptions.TenantId;

            _memoryCache = memoryCache;
        }
示例#18
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder()
                                        .RequireAssertion(_ => true)
                                        .Build();
            });

            System.Diagnostics.Trace.WriteLine("Configuring services in non-production environment");
            AzureAdOptions opts = new AzureAdOptions();

            Configuration.Bind("AzureAd", opts);
            AzureAdOptions.Settings = opts;

            services.AddMvc().AddSessionStateTempDataProvider();
            services.AddSession();
        }
示例#19
0
        public override async Task <AuthenticationResult> TokenForCurrentUser(string[] scope)
        {
            StringValues?ids = httpContextAccessor?.HttpContext?.Request?.Headers["x-userid"];
            var          id  = ids?.FirstOrDefault();

            StringValues?usernames = httpContextAccessor?.HttpContext?.Request?.Headers["x-username"];
            var          username  = usernames?.FirstOrDefault() ?? fakeAuthOptions.Value.DefaultUserName;

            FakeUser?user = id == null && username == null
                ? null //fakeAuthOptions.Value.Users?.FirstOrDefault(v => v.UserName == fakeAuthOptions.Value.DefaultUserName)
                : fakeAuthOptions.Value.Users?.FirstOrDefault(v => v.UserName == username);

            if (user == null)
            {
                return(null);
            }

            AzureAdOptions aad          = aadOptions.Value;
            var            tenantId     = aad.TenantId;
            var            clientId     = aad.ClientId;
            var            clientSecret = aad.ClientSecret;

            HttpClient client = clientFactory.CreateClient();

            PasswordFlow.AccessTokenResponse result = await client.GetMsAccessTokentWithUsernamePassword(
                clientSecret,
                user.UserName,
                user.Password,
                clientId,
                tenantId);

            return(new AuthenticationResult(
                       accessToken: result.access_token,
                       isExtendedLifeTimeToken: true,
                       uniqueId: Guid.NewGuid().ToString(),
                       expiresOn: DateTimeOffset.Now,
                       extendedExpiresOn: DateTimeOffset.Now,
                       tenantId: tenantId,
                       account: null,
                       idToken: null,
                       scopes: scope,
                       correlationId: Guid.NewGuid()));
        }
        public KeyVaultAdminService(IOptionsSnapshot <AzureAdOptions> azureAdOptions, IOptionsSnapshot <AdminConfig> adminConfig, IOptionsSnapshot <Resources> resources, IGraphHttpService graphHttpService, IHttpContextAccessor contextAccessor)
        {
            var principal = contextAccessor.HttpContext.User;

            userId   = principal.FindFirst("oid").Value;
            tenantId = Guid.Parse(principal.FindFirst("tid").Value);
            clientId = Guid.Parse(azureAdOptions.Value.ClientId);

            adalContext       = new AuthenticationContext($"{azureAdOptions.Value.AADInstance}{azureAdOptions.Value.TenantId}", new ADALSessionCache(userId, contextAccessor));
            resourceGroup     = adminConfig.Value.ResourceGroup;
            kvManagmentClient = new KeyVaultManagementClient(new KeyVaultCredential(GetAppToken));
            kvManagmentClient.SubscriptionId = adminConfig.Value.SubscriptionId;
            kvClient = new KeyVaultClient(new KeyVaultCredential(GetAppTokenForKv));

            this.azureAdOptions   = azureAdOptions.Value;
            this.adminConfig      = adminConfig.Value;
            this.graphHttpService = graphHttpService;
            this.resources        = resources.Value;
        }
        public static async Task CheckToken(ClaimsIdentity identity, AzureAdOptions azureAdOptions)
        {
            if (!string.IsNullOrEmpty(token))
            {
                return;
            }

            ClientCredential clientCred = new ClientCredential(azureAdOptions.ClientId, azureAdOptions.ClientSecret);

            string        userAccessToken = identity.BootstrapContext as string;
            string        userName        = identity.Name;
            UserAssertion userAssertion   = new UserAssertion(userAccessToken, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);

            string authority = $"{azureAdOptions.Instance}{azureAdOptions.Domain}";
            AuthenticationContext authContext = new AuthenticationContext(authority);

            var result = await authContext.AcquireTokenAsync(Constants.ResourceUrl, clientCred, userAssertion);

            token = result.AccessToken;
        }
示例#22
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var azureOptions = new AzureAdOptions();

            Configuration.Bind("AzureAd", azureOptions);

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddOptions();

            services.AddApiService(Configuration);
            services.AddTransient <IAssignedUserService, AssignedUserService>();

            services.AddRazorPages();
        }
示例#23
0
        /// <summary>
        /// Configure Graph Component.
        /// </summary>
        /// <param name="services">IServiceCollection .</param>
        /// <param name="configuration">IConfiguration .</param>
        /// <returns>..</returns>
        public static IServiceCollection ConfigureGraphComponent(this IServiceCollection services, Action <AzureAdOptions> azureAdOptionsAction)
        {
            var options = new AzureAdOptions();

            azureAdOptionsAction(options);

            IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
                                                                           .Create(options.ClientId)
                                                                           .WithTenantId(options.TenantId)
                                                                           .WithClientSecret(options.ClientSecret)
                                                                           .Build();

            ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);

            services.AddScoped <IGraphServiceClient, GraphServiceClient>(sp =>
            {
                return(new GraphServiceClient(authenticationProvider));
            });

            return(services);
        }
        public DomainResolver(HttpContext httpContext, AzureAdOptions azureAdOptions, AzureAdB2COptions azureAdB2COptions)
        {
            _azureAdOptions    = azureAdOptions;
            _azureAdB2COptions = azureAdB2COptions;

            _httpContext = httpContext;
            userObjectID = (httpContext.User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;

            if (httpContext.User.FindFirst("emails") != null)
            {
                signedInUseremail = httpContext.User.FindFirst("emails").Value;
            }
            else
            {
                //"preferred_username"
                signedInUseremail = httpContext.User.FindFirst("preferred_username") != null?httpContext.User.FindFirst("preferred_username").Value : null;
            }
            if (!signedInUseremail.ToLower().EndsWith("domain.com"))
            {
                isB2cUser = true;
            }
        }
        public AuthorizationService(
            ILogger <AuthorizationService> logger,
            IOptionsMonitor <AppOptions> appOptions,
            IUserProfileRepository userProfileRepository,
            IRoleRepository roleRepository,
            IPermissionRepository permissionRepository,
            IMemoryCache cache,
            IConfiguration configuration,
            IUserContext userContext) : base(logger, appOptions)
        {
            Guard.Against.Null(userProfileRepository, nameof(userProfileRepository));
            Guard.Against.Null(roleRepository, nameof(roleRepository));
            _userProfileRepository = userProfileRepository;
            _roleRepository        = roleRepository;
            _permissionRepository  = permissionRepository;
            _userContext           = userContext;
            _overrdingAccess       = false;

            var azureOptions = new AzureAdOptions();

            configuration.Bind("AzureAd", azureOptions);
            _clientId = azureOptions.ClientId;
        }
示例#26
0
        public TeamChannelService(
            ILogger <TeamChannelService> logger,
            IOptionsMonitor <AppOptions> appOptions,
            IAuthorizationService authorizationService,
            IPermissionRepository permissionRepository,
            Infrastructure.Services.GraphUserAppService graphUserAppService,
            Infrastructure.Services.GraphTeamsAppService graphTeamsAppService,
            Infrastructure.Services.GraphTeamsOnBehalfService graphTeamsOnBehalfService,
            IAddInHelper addInHelper,
            IConfiguration configuration,
            CardNotificationService cardNotificationService) : base(logger, appOptions)
        {
            Guard.Against.Null(logger, nameof(logger));
            Guard.Against.Null(appOptions, nameof(appOptions));
            Guard.Against.Null(cardNotificationService, nameof(cardNotificationService));
            Guard.Against.Null(authorizationService, nameof(authorizationService));
            Guard.Against.Null(permissionRepository, nameof(permissionRepository));

            Guard.Against.Null(graphUserAppService, nameof(graphUserAppService));
            Guard.Against.Null(graphTeamsAppService, nameof(graphTeamsAppService));
            Guard.Against.Null(graphTeamsOnBehalfService, nameof(graphTeamsOnBehalfService));
            Guard.Against.Null(addInHelper, nameof(addInHelper));


            var azureOptions = new AzureAdOptions();

            configuration.Bind("AzureAd", azureOptions);

            _graphUserAppService       = graphUserAppService;
            _cardNotificationService   = cardNotificationService;
            _authorizationService      = authorizationService;
            _permissionRepository      = permissionRepository;
            _graphTeamsAppService      = graphTeamsAppService;
            _graphTeamsOnBehalfService = graphTeamsOnBehalfService;
            _addInHelper = addInHelper;
            _baseUrl     = azureOptions.BaseUrl;
        }
 public ConfigureAzureOptions(IOptions <AzureAdOptions> azureOptions)
 {
     _azureOptions = azureOptions.Value;
 }
示例#28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            // This custom provider allows able to use just [Authorize] instead of having to define [Authorize(AuthenticationSchemes = "Bearer")] above every API controller
            // without this Bearer authorization will not work
            services.AddSingleton <IAuthenticationSchemeProvider, CustomAuthenticationSchemeProvider>();

            services.AddRedis(Configuration);

            services.AddSignalR().AddPushNotifications(Configuration);

            services.AddOptions <PlatformOptions>().Bind(Configuration.GetSection("VirtoCommerce")).ValidateDataAnnotations();
            services.AddOptions <TranslationOptions>().Configure(options =>
            {
                options.PlatformTranslationFolderPath = WebHostEnvironment.MapPath(options.PlatformTranslationFolderPath);
            });
            //Get platform version from GetExecutingAssembly
            PlatformVersion.CurrentVersion = SemanticVersion.Parse(FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion);

            services.AddPlatformServices(Configuration);
            services.AddSecurityServices();
            services.AddSingleton <LicenseProvider>();

            // The following line enables Application Insights telemetry collection.
            services.AddApplicationInsightsTelemetry();
            services.AddApplicationInsightsTelemetryProcessor <IgnoreSignalRTelemetryProcessor>();

            var mvcBuilder = services.AddMvc(mvcOptions =>
            {
                //Disable 204 response for null result. https://github.com/aspnet/AspNetCore/issues/8847
                var noContentFormatter = mvcOptions.OutputFormatters.OfType <HttpNoContentOutputFormatter>().FirstOrDefault();
                if (noContentFormatter != null)
                {
                    noContentFormatter.TreatNullValueAsNoContent = false;
                }
            }
                                             )
                             .AddNewtonsoftJson(options =>
            {
                //Next line needs to represent custom derived types in the resulting swagger doc definitions. Because default SwaggerProvider used global JSON serialization settings
                //we should register this converter globally.
                options.SerializerSettings.ContractResolver = new PolymorphJsonContractResolver();
                //Next line allow to use polymorph types as parameters in API controller methods
                options.SerializerSettings.Converters.Add(new StringEnumConverter());
                options.SerializerSettings.Converters.Add(new PolymorphJsonConverter());
                options.SerializerSettings.Converters.Add(new ModuleIdentityJsonConverter());
                options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
                options.SerializerSettings.ReferenceLoopHandling      = ReferenceLoopHandling.Ignore;
                options.SerializerSettings.DateTimeZoneHandling       = DateTimeZoneHandling.Utc;
                options.SerializerSettings.NullValueHandling          = NullValueHandling.Ignore;
                options.SerializerSettings.Formatting = Formatting.None;
            }
                                                );

            services.AddSingleton(js =>
            {
                var serv = js.GetService <IOptions <MvcNewtonsoftJsonOptions> >();
                return(JsonSerializer.Create(serv.Value.SerializerSettings));
            });

            services.AddDbContext <SecurityDbContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("VirtoCommerce"));
                // Register the entity sets needed by OpenIddict.
                // Note: use the generic overload if you need
                // to replace the default OpenIddict entities.
                options.UseOpenIddict();
            });

            // Enable synchronous IO if using Kestrel:
            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // Enable synchronous IO if using IIS:
            services.Configure <IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var authBuilder = services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                              //Add the second ApiKey auth schema to handle api_key in query string
                              .AddScheme <ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(ApiKeyAuthenticationOptions.DefaultScheme, options => { })
                              .AddCookie();

            services.AddSecurityServices(options =>
            {
            });

            services.AddIdentity <ApplicationUser, Role>(options => options.Stores.MaxLengthForKeys = 128)
            .AddEntityFrameworkStores <SecurityDbContext>()
            .AddDefaultTokenProviders();

            // Configure Identity to use the same JWT claims as OpenIddict instead
            // of the legacy WS-Federation claims it uses by default (ClaimTypes),
            // which saves you from doing the mapping in your authorization controller.
            services.Configure <IdentityOptions>(options =>
            {
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.UserIdClaimType   = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.RoleClaimType     = OpenIdConnectConstants.Claims.Role;
            });

            // Support commonly used forwarded headers
            // X-Forwarded-For - Holds Client IP (optionally port number) across proxies and ends up in HttpContext.Connection.RemoteIpAddress
            // X-Forwarded-Proto - Holds original scheme (HTTP or HTTPS) even if call traversed proxies and changed and ends up in HttpContext.Request.Scheme
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.KnownProxies.Clear();
                options.ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor;
            });

            //Create backup of token handler before default claim maps are cleared
            var defaultTokenHandler = new JwtSecurityTokenHandler();

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
            authBuilder.AddJwtBearer(options =>
            {
                options.Authority = Configuration["Auth:Authority"];
                options.Audience  = Configuration["Auth:Audience"];

                if (WebHostEnvironment.IsDevelopment())
                {
                    options.RequireHttpsMetadata = false;
                }

                options.IncludeErrorDetails = true;

                X509SecurityKey publicKey = null;
                if (!Configuration["Auth:PublicCertPath"].IsNullOrEmpty())
                {
                    var publicCert = new X509Certificate2(Configuration["Auth:PublicCertPath"]);
                    publicKey      = new X509SecurityKey(publicCert);
                }

                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    NameClaimType            = OpenIdConnectConstants.Claims.Subject,
                    RoleClaimType            = OpenIdConnectConstants.Claims.Role,
                    ValidateIssuer           = !string.IsNullOrEmpty(options.Authority),
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = publicKey
                };
            });

            var azureAdSection = Configuration.GetSection("AzureAd");

            if (azureAdSection.GetChildren().Any())
            {
                var options = new AzureAdOptions();
                azureAdSection.Bind(options);

                if (options.Enabled)
                {
                    //TODO: Need to check how this influence to OpennIddict Reference tokens activated by this line below  AddValidation(options => options.UseReferenceTokens());
                    authBuilder.AddOpenIdConnect(options.AuthenticationType, options.AuthenticationCaption,
                                                 openIdConnectOptions =>
                    {
                        openIdConnectOptions.ClientId               = options.ApplicationId;
                        openIdConnectOptions.Authority              = $"{options.AzureAdInstance}{options.TenantId}";
                        openIdConnectOptions.UseTokenLifetime       = true;
                        openIdConnectOptions.RequireHttpsMetadata   = false;
                        openIdConnectOptions.SignInScheme           = IdentityConstants.ExternalScheme;
                        openIdConnectOptions.SecurityTokenValidator = defaultTokenHandler;
                    });
                }
            }

            services.AddOptions <Core.Security.AuthorizationOptions>().Bind(Configuration.GetSection("Authorization")).ValidateDataAnnotations();
            var authorizationOptions = Configuration.GetSection("Authorization").Get <Core.Security.AuthorizationOptions>();
            var platformOptions      = Configuration.GetSection("VirtoCommerce").Get <PlatformOptions>();

            // Register the OpenIddict services.
            // Note: use the generic overload if you need
            // to replace the default OpenIddict entities.
            services.AddOpenIddict()
            .AddCore(options =>
            {
                options.UseEntityFrameworkCore()
                .UseDbContext <SecurityDbContext>();
            }).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, logout, token and userinfo endpoints.
                options.EnableTokenEndpoint("/connect/token")
                .EnableUserinfoEndpoint("/api/security/userinfo");

                // Note: the Mvc.Client sample only uses the code flow and the password flow, but you
                // can enable the other flows if you need to support implicit or client credentials.
                options.AllowPasswordFlow()
                .AllowRefreshTokenFlow()
                .AllowClientCredentialsFlow();

                options.SetRefreshTokenLifetime(authorizationOptions?.RefreshTokenLifeTime);
                options.SetAccessTokenLifetime(authorizationOptions?.AccessTokenLifeTime);

                options.AcceptAnonymousClients();

                // Configure Openiddict to issues new refresh token for each token refresh request.
                options.UseRollingTokens();

                // Make the "client_id" parameter mandatory when sending a token request.
                //options.RequireClientIdentification();

                // When request caching is enabled, authorization and logout requests
                // are stored in the distributed cache by OpenIddict and the user agent
                // is redirected to the same page with a single parameter (request_id).
                // This allows flowing large OpenID Connect requests even when using
                // an external authentication provider like Google, Facebook or Twitter.
                options.EnableRequestCaching();

                options.DisableScopeValidation();

                // During development or when you explicitly run the platform in production mode without https, need to disable the HTTPS requirement.
                if (WebHostEnvironment.IsDevelopment() || platformOptions.AllowInsecureHttp || !Configuration.IsHttpsServerUrlSet())
                {
                    options.DisableHttpsRequirement();
                }

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

                var bytes = File.ReadAllBytes(Configuration["Auth:PrivateKeyPath"]);
                X509Certificate2 privateKey;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    // https://github.com/dotnet/corefx/blob/release/2.2/Documentation/architecture/cross-platform-cryptography.md
                    // macOS cannot load certificate private keys without a keychain object, which requires writing to disk. Keychains are created automatically for PFX loading, and are deleted when no longer in use. Since the X509KeyStorageFlags.EphemeralKeySet option means that the private key should not be written to disk, asserting that flag on macOS results in a PlatformNotSupportedException.
                    privateKey = new X509Certificate2(bytes, Configuration["Auth:PrivateKeyPassword"], X509KeyStorageFlags.MachineKeySet);
                }
                else
                {
                    privateKey = new X509Certificate2(bytes, Configuration["Auth:PrivateKeyPassword"], X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.EphemeralKeySet);
                }
                options.AddSigningCertificate(privateKey);
            });

            services.Configure <IdentityOptions>(Configuration.GetSection("IdentityOptions"));

            //always  return 401 instead of 302 for unauthorized  requests
            services.ConfigureApplicationCookie(options =>
            {
                options.Events.OnRedirectToLogin = context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(Task.CompletedTask);
                };
                options.Events.OnRedirectToAccessDenied = context =>
                {
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(Task.CompletedTask);
                };
            });

            services.AddAuthorization(options =>
            {
                //We need this policy because it is a single way to implicitly use the two schema (JwtBearer and ApiKey)  authentication for resource based authorization.
                var mutipleSchemaAuthPolicy = new AuthorizationPolicyBuilder().AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme, ApiKeyAuthenticationOptions.DefaultScheme)
                                              .RequireAuthenticatedUser()
                                              .Build();
                //The good article is described the meaning DefaultPolicy and FallbackPolicy
                //https://scottsauber.com/2020/01/20/globally-require-authenticated-users-by-default-using-fallback-policies-in-asp-net-core/
                options.DefaultPolicy = mutipleSchemaAuthPolicy;
            });
            // register the AuthorizationPolicyProvider which dynamically registers authorization policies for each permission defined in module manifest
            services.AddSingleton <IAuthorizationPolicyProvider, PermissionAuthorizationPolicyProvider>();
            //Platform authorization handler for policies based on permissions
            services.AddSingleton <IAuthorizationHandler, DefaultPermissionAuthorizationHandler>();
            // Default password validation service implementation
            services.AddScoped <IPasswordCheckService, PasswordCheckService>();

            services.AddOptions <LocalStorageModuleCatalogOptions>().Bind(Configuration.GetSection("VirtoCommerce"))
            .PostConfigure(options =>
            {
                options.DiscoveryPath = Path.GetFullPath(options.DiscoveryPath ?? "modules");
            })
            .ValidateDataAnnotations();
            services.AddModules(mvcBuilder);

            services.AddOptions <ExternalModuleCatalogOptions>().Bind(Configuration.GetSection("ExternalModules")).ValidateDataAnnotations();
            services.AddExternalModules();

            //Assets
            var assetsProvider = Configuration.GetSection("Assets:Provider").Value;

            if (assetsProvider.EqualsInvariant(AzureBlobProvider.ProviderName))
            {
                services.AddOptions <AzureBlobOptions>().Bind(Configuration.GetSection("Assets:AzureBlobStorage")).ValidateDataAnnotations();
                services.AddAzureBlobProvider();
            }
            else
            {
                services.AddOptions <FileSystemBlobOptions>().Bind(Configuration.GetSection("Assets:FileSystem"))
                .PostConfigure(options =>
                {
                    options.RootPath = WebHostEnvironment.MapPath(options.RootPath);
                }).ValidateDataAnnotations();

                services.AddFileSystemBlobProvider();
            }

            //HangFire
            services.AddHangfire(Configuration);

            // Register the Swagger generator
            services.AddSwagger();
        }
示例#29
0
 public MSGraphHelper(IOptions <AzureAdOptions> azureAdOptions, ITokenAcquisition tokenAcquisition)
 {
     _azureAdOptions   = azureAdOptions.Value;
     _tokenAcquisition = tokenAcquisition;
 }
 public AzureADAuthController(IOptions <AzureAdOptions> azureAdOptions, IAssignedUserService assignedUserService)
 {
     _azureAdOptions      = azureAdOptions.Value;
     _assignedUserService = assignedUserService;
 }