Exemple #1
0
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            _stopwatch = new Stopwatch();
            _stopwatch.Start();
            var service            = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var method             = actionContext.ActionDescriptor.ActionName;
            var isAuthenticated    = actionContext.RequestContext.Principal.Identity.IsAuthenticated;
            var identityName       = isAuthenticated ? actionContext.RequestContext.Principal.Identity.Name : null;
            var identityNameExists = !string.IsNullOrWhiteSpace(identityName);

            if (isAuthenticated && identityNameExists)
            {
                if (!ClaimPermission.CheckAccess(ClaimTypes.ExposedService, service, method, identityName))
                {
                    this.HandleUnauthorizedRequest(actionContext);
                }
            }
            else
            {
                // Log this weird case
                if (isAuthenticated && !identityNameExists)
                {
                    log4net.LogManager.GetLogger(nameof(CustomWebApiAuthorizeAttribute)).Warn($"Authenticated user without Identity.Name! Handling as unauthenticated... ({service}/{method})");
                }
                if (!ClaimPermission.CheckAccess(ClaimTypes.ExposedService, service, method))
                {
                    this.HandleUnauthenticatedRequest(actionContext);
                }
            }
        }
 private static void ImperativeUsingPermission()
 {
     ClaimPermission.CheckAccess(
         "ImperativeAction",
         "ImperativeResource",
         new Claim("http://additionalClaim", "AdditionalResource"));
 }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            ValidateRequestHeader(filterContext.HttpContext.Request);
            var controller           = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var getFromFilterContext = string.IsNullOrWhiteSpace(ActionName) || string.IsNullOrWhiteSpace(ClaimType);
            var action    = getFromFilterContext ? filterContext.ActionDescriptor.ActionName : ActionName;
            var claimType = getFromFilterContext ? ClaimTypes.ControllerAction : ClaimType;

            filterContext.HttpContext.Items["_currentControllerAction"] = controller;
            var accessible = ClaimPermission.CheckAccess(claimType, controller, action);

            if (accessible)
            {
                return;
            }
            if (LogEnabled)
            {
                IdentityHelper.LogAction(
                    filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                    filterContext.ActionDescriptor.ActionName,
                    false,
                    "Unauthorized");
            }
            filterContext.Result = PrepareUnauthorizedResult(filterContext);
        }
Exemple #4
0
 private bool ShouldRun()
 {
     if (!ClaimPermission.CheckAccess(ClaimTypes.IDEF0Activity, "WorkflowSock", "ReconnectSockets"))
     {
         IdentityHelper.LogAction("WorkflowSock", "ReconnectSockets", false, "Unauthorized");
         throw new UnauthorizedAccessException("You do not have permissions to execute step 'ReconnectSockets' of 'WorkflowSock' Workflow");
     }
     return(true);
 }
Exemple #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddAutoMapper(typeof(Startup));
            services.AddScoped <IRequestServices, RequestServices>();
            services.Configure <AppSettings>(Configuration.GetSection(AppSettings.Settings));
            services.Configure <JwtOptions>(Configuration.GetSection(JwtOptions.Name));
            services.AddExtCore(_extensions_path, Configuration["Extensions:IncludingSubpaths"] == true.ToString());

            services.AddDbContext <ApplicationDbContext>(options =>
            {
                if (_env.IsDevelopment())
                {
                    options.EnableSensitiveDataLogging();
                }
                options.UseNpgsql(Configuration.GetConnectionString("Default"));
            });
            services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();

            /*
             * services.Configure<MongoSettings>(Configuration.GetSection(nameof(MongoSettings)));
             * services.AddSingleton<IMongoSettings>(x => x.GetRequiredService<IOptions<MongoSettings>>().Value);
             * services.AddSingleton<LoggingDBServices>();
             */

            services.AddScoped(typeof(IStorageContext), typeof(ApplicationDbContext));
            //string[] assembliesIngored = new string[] { "Microsoft.AspNetCore", "Microsoft.Extensions" };
            //services.AddServicesOfType<IScopedService>(assembliesIngored);
            //services.AddServicesWithAttributeOfType<ScopedServiceAttribute>(assembliesIngored);
            services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(@_env.ContentRootPath + "/keys/")).UseCryptographicAlgorithms(new AuthenticatedEncryptorConfiguration()
            {
                EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
                ValidationAlgorithm = ValidationAlgorithm.HMACSHA512
            });

            //services.Configure<FileStorageOptions>(options =>
            //{
            //    options.RootPath = $@"{_env.ContentRootPath}\FileStorage\Uploads";
            //    //options.Secret = "[Dropbox access token]";
            //    //options.RootPath = @"/";
            //});
            //services.AddScoped<IKeyCachingServices, KeyCachingServices>();

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = _JwtOptions.RequireHttps;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_JwtOptions.SecurityKey)),
                    ValidateIssuer           = _JwtOptions.ValidateIssuer,
                    ValidateAudience         = _JwtOptions.ValidateAudience,
                    ValidateLifetime         = true, // Check if the token is not expired and the signing key of the issuer is valid
                    ValidIssuer   = _JwtOptions.Issuer,
                    ValidAudience = _JwtOptions.Audience
                };
            });
            services.AddScoped <IUserServices, UserServices>();
            //services.AddSingleton<IUserServices,UserServices>();
            services.AddSingleton <IRequestServices, RequestServices>();
            services.AddControllers();
            services.AddControllersWithViews().AddNewtonsoftJson(options =>
                                                                 options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                                                                 );

            // List of public directory
            //services.AddDirectoryBrowser();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version        = "v1",
                    Title          = "RTAPP Web API",
                    Description    = "RTAPP base API",
                    TermsOfService = null,
                    Contact        = new OpenApiContact
                    {
                        Name  = "Sornarin (Tom)",
                        Email = "*****@*****.**",
                    },
                    License = new OpenApiLicense
                    {
                        Name = "<- Go back",
                        Url  = new Uri(_appSetting.Hostname)
                    }
                });
                var dir        = AppContext.BaseDirectory + _appSetting.DocumentsPath;
                string[] files = Directory.GetFiles(dir, "*.xml", SearchOption.TopDirectoryOnly);
                foreach (string file in files)
                {
                    c.IncludeXmlComments(Path.Combine(dir, file));
                }
                //var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } },
                // };
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
                c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme()
                {
                    Description = "API Key Authorization header using the custom scheme. Example: \"ApiKey:{key}\"",
                    Name        = "ApiKey",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] { }
                    },
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "ApiKey"
                            }
                        },
                        new string[] { }
                    }
                });
            });

            services.AddCors(policy =>
            {
                policy.AddPolicy("CorsPolicy", opt => opt
                                 .AllowAnyOrigin()
                                 .AllowAnyHeader()
                                 .AllowAnyMethod()
                                 .WithExposedHeaders("X-Pagination"));
            });


            services.AddAuthorization(options =>
            {
                //https://stackoverflow.com/questions/42562660/recommended-best-practice-for-role-claims-as-permissions
                var perms      = new ClaimPermission().GetPermissions();
                var extensions = new List <IExtension>();
                if (_appSetting.AssemblyCandidate)
                {
                    string[] starts = new string[] { "ExtCore" };
                    extensions      = ExtensionManager.GetInstances <IExtension>().Where(x => !starts.Any(sl => x.Name.StartsWith(sl))).ToList();
                }
                else
                {
                    extensions = ExtensionManager.GetInstances <IExtension>().ToList();
                }

                foreach (var ext in extensions)
                {
                    foreach (var perm in perms)
                    {
                        var policy_name = $"{ext.Code}.{perm}";
                        options.AddPolicy(policy_name, policy => policy.RequireClaim(ClaimTypes.Role, policy_name));
                        //options.AddPolicy(policy_name, p => p.Requirements.Add(new PermissionRequirement(policy_name)));
                    }
                }
            });
            //https://devblogs.microsoft.com/aspnet/jwt-validation-and-authorization-in-asp-net-core/
            //services.AddSingleton<IAuthorizationHandler, MaximumOfficeNumberAuthorizationHandler>();

            // WASM
            services.AddRazorPages();
        }
Exemple #6
0
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);//.UseHeadElementServerPrerendering();;

            builder.RootComponents.Add <App>("app");



            //-----------------------------| Register extensions |---------------------------------------
            Modules.Add(typeof(Benriya.Clients.Modules.CMS.ClientMudule));
            Modules.Add(typeof(Benriya.Clients.Modules.Inventory.ClientMudule));
            Modules.Add(typeof(Benriya.Clients.Modules.eCommerce.ClientMudule));



            //builder.RootComponents.Add<MetaData>("head");
            //builder.Services.AddBlazorise(options =>
            // {
            //     options.ChangeTextOnKeyPress = true;
            // }).AddBootstrapProviders().AddFontAwesomeIcons();

            //builder.Services.AddRazorComponentsRuntimeCompilation();
            //builder.Services.AddScoped<MetaDataProvider>();
            #region Register extensions
            //------------------------------- start load extensions
            ModulesSetup();
            //---------------------------------------------------------------------
            #endregion End of load extensions
            var uri = new Uri(CLIENT_CONFIG.API_URL);
            builder.Services.AddScoped <IUrlManager, UrlManager>();
            builder.Services.AddScoped <IAuthenServices, AuthenServices>();
            builder.Services.AddScoped(typeof(IApiClientService <>), typeof(ApiClientService <>));
            builder.Services.AddBlazoredToast();
            builder.Services.AddHeadElementHelper();
            builder.Services.AddBlazoredLocalStorage(config => config.JsonSerializerOptions.WriteIndented   = true);
            builder.Services.AddBlazoredSessionStorage(config => config.JsonSerializerOptions.WriteIndented = true);
            builder.Services.AddAuthorizationCore();
            builder.Services.AddScoped <AuthenticationStateProvider, ApiAuthenticationStateProvider>();
            builder.Services.AddScoped <IApiServiceProvider, ApiServiceProvider>();
            builder.Services.AddScoped(sp => new HttpClient {
                BaseAddress = uri
            });                                                                    // builder.HostEnvironment.BaseAddress) });
            builder.Services.AddI18nText();
            builder.Services.AddLoadingComponent();
            builder.Services.AddFileReaderService(o => { o.UseWasmSharedBuffer = true; });

            var client = new HttpClient {
                BaseAddress = uri
            };
            builder.Services.AddAuthorizationCore(async options =>
            {
                var perms  = new ClaimPermission().GetPermissions();
                var client = new HttpClient {
                    BaseAddress = uri
                };
                var response = await client.GetFromJsonAsync <ApiResultModel <List <ExtensionModel> > >($"core/Modules");
                //var policies = new Dictionary<string,string>();
                if (response != null && response.Status == 200 && response.Data != null)
                {
                    foreach (var ext in response.Data)
                    {
                        foreach (var perm in perms)
                        {
                            var policy_name = $"{ext.Code}.{perm}";
                            //policies.Add(policy_name,policy_name);
                            options.AddPolicy(policy_name, policy => policy.RequireClaim(ClaimTypes.Role, policy_name));
                        }
                    }
                }
            });

            // builder
            //---------------------------------
            var host = builder.Build();

            var response = await client.GetFromJsonAsync <ApiResultModel <string> >($"core/Sys/Version");

            if (response != null && response.Status == 200)
            {
                var sessionStorage = host.Services.GetRequiredService <ISessionStorageService>();
                await sessionStorage.SetItemAsync <string>(AppClient.VersionKey, response.Data);

                sessionStorage = null;
            }

            //---------------------------------
            //host.Services.UseBootstrapProviders().UseFontAwesomeIcons();
            //if(policies)
            //var sessionStorage = host.Services.GetRequiredService<ISessionStorageService>();

            //await builder.Build().RunAsync();
            await host.RunAsync();
        }
        public async Task <bool> SetupMudules()
        {
            try
            {
                var perms      = new ClaimPermission().GetPermissions();
                var extensions = new List <IExtension>();

                var all_policy_db = await dbSet.AsNoTracking().ToListAsync();

                var admin_role_db = this.storageContext.Set <User_Role>();
                var admin_codes   = new string[] { "admin", "system", "systemadmin", "system_admin" };
                var admin_roles   = await admin_role_db.AsNoTracking().Where(x => admin_codes.Contains(x.code.ToLower())).ToListAsync();

                if (admin_roles.Count() == 0)
                {
                    admin_roles = new List <User_Role>()
                    {
                        new User_Role()
                        {
                            code = "SYSTEM", name = "System", role_level = 30
                        },
                        new User_Role()
                        {
                            code = "SYSTEM_ADMIN", name = "System admin", role_level = 29
                        },
                        new User_Role()
                        {
                            code = "ADMIN", name = "Administrator", role_level = 28
                        },
                    };
                    await admin_role_db.AddRangeAsync(admin_roles);

                    await storageContext.SaveChangesAsync();
                }

                if (Client.ServerSettings.AssemblyCandidate)
                {
                    string[] starts = new string[] { "ExtCore" };
                    extensions = ExtensionManager.GetInstances <IExtension>().Where(x => !starts.Any(sl => x.Name.StartsWith(sl))).ToList();
                }
                else
                {
                    extensions = ExtensionManager.GetInstances <IExtension>().ToList();
                }

                var permission_context = this.storageContext.Set <Permission_Access>();
                var all_permission_db  = await permission_context.AsNoTracking().ToListAsync();

                all_permission_db.ForEach(x => { x.is_active = false; });

                if (all_permission_db.Count() > 0)
                {
                    return(false);
                }

                //var new_perms = new List<Permission_Access>();
                var new_pols = new List <Policy_Roles>();

                foreach (var perm in perms)
                {
                    var new_perm = new Permission_Access()
                    {
                        name        = perm,
                        is_active   = true,
                        code        = perm,
                        description = perm
                    };
                    await permission_context.AddAsync(new_perm);

                    await storageContext.SaveChangesAsync();

                    foreach (var ext in extensions)
                    {
                        var policy_code = $"{ext.Code}.{perm}";
                        foreach (var role in admin_roles)
                        {
                            new_pols.Add(new Policy_Roles()
                            {
                                role_id       = role.id,
                                permission_id = new_perm.id,
                                code          = policy_code,
                                module_name   = ext.Name,
                                module_code   = ext.Code,
                                User_Role     = null,
                                Permission    = null
                            });
                        }
                    }
                }
                await dbSet.AddRangeAsync(new_pols);

                await storageContext.SaveChangesAsync();

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }