public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpContext httpContext = filterContext.HttpContext; Controller control = filterContext.Controller as Controller; string BRE_NO = CheckBRE_NO != null ? CheckBRE_NO : control.RouteData.Values["Controller"].ToString(); string ACTION_ID = CheckACTION_ID != null ? CheckACTION_ID : control.RouteData.Values["action"].ToString(); if (!CheckDbPermissson(httpContext.User.Identity.GetClaimValue(ClaimTypes.NameIdentifier))) { if (ClientHelpers.IsAjaxRequest(httpContext.Request) || ClientHelpers.IsApiRequest(httpContext.Request)) { var data = "{ \"Success\" : \"false\" , \"Error\" : \"您無權異動資料\" }"; var JsonResult = new JsonResult(data); filterContext.Result = JsonResult; } else { filterContext.Result = new ForbidResult(); } } base.OnActionExecuting(filterContext); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { #region Authorize // Add authentication services services.AddAuthentication(options => { options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme; }) .AddCookie(options => { /* Cookies Authorize */ options.LoginPath = "/Account/Login"; options.AccessDeniedPath = "/Error/AccessDenied"; options.Events.OnRedirectToLogin = ctx => { if (!(ClientHelpers.IsAjaxRequest(ctx.Request) || ClientHelpers.IsApiRequest(ctx.Request))) { ctx.Response.Redirect(ctx.RedirectUri); return(Task.CompletedTask); } ctx.Response.StatusCode = StatusCodes.Status401Unauthorized; return(ctx.Response.WriteAsync("Unauthorized")); }; options.Events.OnRedirectToAccessDenied = ctx => { if (!(ClientHelpers.IsAjaxRequest(ctx.Request) || ClientHelpers.IsApiRequest(ctx.Request))) { ctx.Response.Redirect(options.AccessDeniedPath); return(Task.CompletedTask); } ctx.Response.StatusCode = StatusCodes.Status401Unauthorized; return(ctx.Response.WriteAsync("Your member's authority is not enough.")); }; }) .AddJwtBearer(options => { /* 驗證 Json Web Token 對應 */ options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Tokens:ValidIssuer"], ValidAudience = Configuration["Tokens:ValidAudience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:IssuerSigningKey"])), RequireExpirationTime = true, }; options.Events = new JwtBearerEvents() { OnAuthenticationFailed = context => { context.NoResult(); context.Response.StatusCode = StatusCodes.Status401Unauthorized; return(Task.CompletedTask); }, OnTokenValidated = context => { Console.WriteLine("OnTokenValidated: " + context.SecurityToken); return(Task.CompletedTask); } }; }); // Policy (權限群組設定) services.AddAuthorization(options => { options.AddPolicy(nameof(PolicyGroup.管理者級別), policy => policy.RequireRole(nameof(UserRole.最大管理者), nameof(UserRole.管理者))); options.AddPolicy(nameof(PolicyGroup.基層級別), policy => policy.RequireRole(nameof(UserRole.一般會員))); }); #endregion #region Dependency Injection // 注入Config var configManager = new ConfigManager(); Configuration.GetSection("Config").Bind(configManager); Mapper.Initialize(cfg => cfg.CreateMap <ConfigManager, ConfigManager>()); ConfigProvider.ConfigManager = Mapper.Map <ConfigManager>(configManager); // 注入Unit、DAL、Service services.AddScoped <IUnitOfWork, UnitOfWork>(); services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>)); services.AddScoped <IUserService, UserService>(); services.AddScoped <IBulletinService, BulletinService>(); // 注入DbContext services.AddDbContext <HRTrainDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection"))); // 注入IMapper services.AddAutoMapper(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); // 注入建構子可加入 IHttpContextAccessor 可取得 HttpContext #endregion #region 多國語系 services.AddLocalization(s => s.ResourcesPath = "Resources"); var supportedCultures = new CultureInfo[] { new CultureInfo("zh-TW"), new CultureInfo("en-GB"), }; services.Configure <RequestLocalizationOptions>(s => { // Formatting numbers, dates, etc. s.SupportedCultures = supportedCultures; // UI strings that we have localized. s.SupportedUICultures = supportedCultures; s.DefaultRequestCulture = new RequestCulture(culture: "zh-TW", uiCulture: "zh-TW"); }); services.AddMvc() .AddViewLocalization() .AddDataAnnotationsLocalization(o => { o.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(SharedResource)); }); #endregion services.AddMvc() .AddJsonOptions(options => { /* 去除循環參考 */ options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); #if DEBUG this.DEVELOP_SEED(); #endif }