private async Task DeleteFile(HttpContext context) { var fileRepositoryIdStr = context.Request.Query["id"]; if (int.TryParse(fileRepositoryIdStr, out int fileRepositoryId)) { //Scope name: AutofacWebRequest is mandatory to match the WebApi scope created. //If the scope is changed some injections stop working with the message that "AutofacWebRequest" scope was not found. using (var scope = IoCGlobal.NewScope("AutofacWebRequest")) { try { var getFileDataRetriever = IoCGlobal.Resolve <IFileRetriever>(null, scope); var fileInfoResult = getFileDataRetriever.GetFileData(fileRepositoryId); var fileInfo = fileInfoResult.Bag; var fileDeleteResult = getFileDataRetriever.DeleteFile(fileRepositoryId); if (!fileInfoResult.IsSucceed) { return; } //string mimeType = null; //var fileStorageService = IoCGlobal.Resolve<IFileStorageService>(fileInfo.FileSystemTypeId, scope); //byte[] result = null; //result = await fileStorageService.RetrieveFile(fileInfo.RootPath, fileInfo.AccessPath, fileInfo.RelativePath, fileInfo.FileName); //mimeType = FileHelpers.GetMimeTypeByExtension(fileInfo.FileName); //context.Response.OnStarting(state => //{ // var httpContext = (HttpContext)state; // httpContext.Response.ContentType = mimeType; // return Task.FromResult(0); //}, context); //var memStream = new MemoryStream(result); //memStream.CopyTo(context.Response.Body); //context.Response.ContentType = mimeType; context.Response.Body.Flush(); } catch (Exception ex) { Logger.Error($"File Delete - {fileRepositoryId}", ex); throw; } return; } } }
private async Task SecuritySeed() { try { Logger.Info("Application startup - Initializing the Authentication Seeding for Administration user"); var adminUserName = "******"; var adminFirstName = "Administrator"; var adminLastName = "Administrator"; var adminUserEmail = "*****@*****.**"; var adminUserPassword = "******"; var adminRoleName = "Administrator"; using (var userManager = IoCGlobal.Resolve <UserManager <AppUser> >()) { using (var roleManager = IoCGlobal.Resolve <RoleManager <IdentityRole> >()) { var adminUser = await userManager.FindByEmailAsync(adminUserEmail); if (adminUser == null) { var newAdminUser = new AppUser { UserName = adminUserName, FirstName = adminFirstName, LastName = adminLastName, Email = adminUserEmail, }; await userManager.CreateAsync(newAdminUser, adminUserPassword); adminUser = await userManager.FindByEmailAsync(adminUserEmail); } var adminRole = await roleManager.FindByNameAsync(adminRoleName); if (adminRole == null) { var newAdminRole = new IdentityRole { Name = adminRoleName, }; await roleManager.CreateAsync(newAdminRole); adminRole = await roleManager.FindByNameAsync(adminRoleName); } await userManager.AddToRoleAsync(adminUser, adminRoleName); var roleClaims = (await roleManager.GetClaimsAsync(adminRole)).Select(o => o.Value); var claimNames = Enum.GetNames(typeof(PermissionsEnum.Enum)).Except(roleClaims); foreach (var permission in claimNames) { await roleManager.AddClaimAsync(adminRole, new Claim(RiverdaleMainApp2_0.Auth.Constants.Strings.JwtClaimIdentifiers.Permissions, permission)); } } } } catch (Exception ex) { Logger.Fatal("Application startup - Execption on Authentication Seeding for Administration user", ex); } finally { Logger.Info("Application startup - Ending the Authentication Seeding for Administration user"); Logger.FlushBuffers(); } }
private void ConfigureAuthenticationServices(IServiceCollection services) { try { Logger.Info("Application startup - Initializing the Infra Authentication/Authorization Configuration"); services.TryAddTransient <IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton <IJwtFactory, JwtFactory>(); // jwt wire up // Get options from app settings var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions)); // Configure JwtIssuerOptions services.Configure <JwtIssuerOptions>(options => { options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)]; options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)]; options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256); }); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)], ValidateAudience = true, ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)], ValidateIssuerSigningKey = true, IssuerSigningKey = _signingKey, RequireExpirationTime = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); // => remove default claims services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, configureOptions => { configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)]; configureOptions.TokenValidationParameters = tokenValidationParameters; configureOptions.RequireHttpsMetadata = false; configureOptions.SaveToken = true; configureOptions.Events = new JwtBearerEvents { OnTokenValidated = context => { // Add the access_token as a claim, as we may actually need it var accessToken = context.SecurityToken as JwtSecurityToken; if (accessToken != null) { ClaimsIdentity identity = context.Principal.Identity as ClaimsIdentity; if (identity != null) { identity.AddClaim(new Claim("access_token", accessToken.RawData)); } // Set Current User var idClaim = identity.FindFirst("id"); if (idClaim != null) { // get claim containing user id var id = idClaim.Value; using (var currentUserService = IoCGlobal.Resolve <ICurrentUserService>()) { currentUserService.CurrentUserId = id; } } } return(Task.CompletedTask); } }; }); // api user claim policy services.AddAuthorization(options => { options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess)); options.AddPolicy(nameof(Constants.Strings.JwtClaims.Administrator), policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.Administrator)); var permissionNames = Enum.GetNames(typeof(PermissionsEnum.Enum)); PolicyPermissionRequired.BuildPolicies(options, permissionNames); }); services.AddHttpClient <CustomHttpClient>(); // add identity var builder = services.AddIdentityCore <AppUser> (o => { // configure identity options o.Password.RequireDigit = false; o.Password.RequireLowercase = false; o.Password.RequireUppercase = false; o.Password.RequireNonAlphanumeric = false; o.Password.RequiredLength = 6; }); builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services); builder.AddRoleValidator <RoleValidator <IdentityRole> >(); builder.AddRoleManager <RoleManager <IdentityRole> >(); builder.AddSignInManager <SignInManager <AppUser> >(); builder.AddEntityFrameworkStores <IdentityDBContext>() .AddDefaultTokenProviders(); } catch (Exception ex) { Logger.Fatal("Application startup - Execption on Infra Authentication/Authorization Configuration", ex); } finally { Logger.Info("Application startup - Ending the Infra Authentication/Authorization Configuration"); Logger.FlushBuffers(); } }
public OperationResponse <FileInsertCommandOutputDTO> Execute <T, A>(T input) where T : FileArgs <A> where A : UploadedFile { //using (var transaction = new TransactionScope()) //{ DomainModel.File.File file = null; var defaultFileStorageId = (string)typeof(FileSourceEnum).GetStaticPropertyValue(AppConfig.Instance.FileStorageSettings.DefaultFileStorageDestination); var fileStorageTypeId = input.FileSource ?? defaultFileStorageId; var result = new OperationResponse <FileInsertCommandOutputDTO>(); using (var dbContextScope = this.DbContextScopeFactory.Create()) { file = new DomainModel.File.File { RootPath = FileInsertCommand.FirstStepDefaultFileName, AccessPath = FileInsertCommand.FirstStepDefaultAccessPath, RelativePath = FileInsertCommand.FirstStepDefaultFolderPath, FileName = FileInsertCommand.FirstStepDefaultFileName, FileSize = input.UploadedFile.ContentLength, ThumbnailFileSize = input.UploadedFile.ThumbnailContent.Length }; OperationResponse <DomainModel.File.File> fileInsertResult = null; // First step. Save file without paths. fileInsertResult = this.Repository.Insert(file); result.AddResponse(fileInsertResult); // Second step. Store file and grab its path details. input.FilePrefix = file.Id.ToString(); FileStorageResultDTO fileStorageResult; using (var scope = IoCGlobal.NewScope("FileStorageScope")) { var fileStorage = IoCGlobal.Resolve <IFileStorageService>(fileStorageTypeId, scope); fileStorageResult = fileStorage.Save(input); } file.RootPath = fileStorageResult.RootPath; file.AccessPath = fileStorageResult.AccessPath; file.RelativePath = fileStorageResult.FolderPath; file.FileName = fileStorageResult.FileName; file.FullFilePath = fileStorageResult.FullFilePath; file.ThumbnailFileName = fileStorageResult.ThumbnailFileName; file.ThumbnailFullFilePath = fileStorageResult.ThumbnailFullFilePath; file.FileSystemTypeId = fileStorageResult.FileSourceId; dbContextScope.SaveChanges(); var getById = this.Repository.GetById(file.Id); result.AddResponse(getById); if (result.IsSucceed) { result.Bag = new FileInsertCommandOutputDTO { Id = getById.Bag.Id }; } else { this.Logger.Error("Error retrieving File", new OperationResponseException(result)); } return(result); } }
private async Task RetrieveFile(HttpContext context) { var fileRepositoryIdStr = context.Request.Query["id"]; bool returnThumbNail = true; { var returnThumbnailStr = context.Request.Query["thumbnail"]; bool.TryParse(returnThumbnailStr, out returnThumbNail); } if (int.TryParse(fileRepositoryIdStr, out int fileRepositoryId)) { //Scope name: AutofacWebRequest is mandatory to match the WebApi scope created. //If the scope is changed some injections stop working with the message that "AutofacWebRequest" scope was not found. using (var scope = IoCGlobal.NewScope("AutofacWebRequest")) { try { var getFileDataRetriever = IoCGlobal.Resolve <IFileRetriever>(null, scope); var fileInfoResult = getFileDataRetriever.GetFileData(fileRepositoryId); if (!fileInfoResult.IsSucceed || fileInfoResult.Bag == null) { throw new Exception(); } var fileInfo = fileInfoResult.Bag; string mimeType = null; var fileStorageService = IoCGlobal.Resolve <IFileStorageService>(fileInfo.FileSystemTypeId, scope); byte[] result = null; if (returnThumbNail) { var thumbnailFileName = fileInfo.ThumbnailFileName ?? fileInfo.FileName; result = await fileStorageService.RetrieveFile(fileInfo.RootPath, fileInfo.AccessPath, fileInfo.RelativePath, thumbnailFileName); mimeType = FileHelpers.GetMimeTypeByExtension(thumbnailFileName); } else { result = await fileStorageService.RetrieveFile(fileInfo.RootPath, fileInfo.AccessPath, fileInfo.RelativePath, fileInfo.FileName); mimeType = FileHelpers.GetMimeTypeByExtension(fileInfo.FileName); } if (result == null || result.Length == 0) { throw new FileNotFoundException(); } context.Response.OnStarting(state => { var httpContext = (HttpContext)state; httpContext.Response.ContentType = mimeType; return(Task.FromResult(0)); }, context); var memStream = new MemoryStream(result); memStream.CopyTo(context.Response.Body); //context.Response.ContentType = mimeType; context.Response.Body.Flush(); } catch (Exception ex) { Logger.Error($"File Retrieve - {fileRepositoryId}", ex); throw; } return; } } else { throw new Exception(); } }