Серьезно, что я здесь не так делаю?Как это может не сработать, если другая политика противоположна другой?только 3 буквы в имени меняются и обратная логическая проверка ....
действует политика HasArranqueActivo
.Я использовал отладчик для тестирования, и он запускает его.
Здесь объявлены политики
services.AddAuthorization(options =>
{
options.AddPolicy("HasArranqueActivo", policy =>
policy.Requirements.Add(new HasArranqueActivoRequirement()
));
options.AddPolicy("HasArranqueInactivo", policy =>
policy.Requirements.Add(new HasArranqueInactivoRequirement()
));
});
Как вы можете видеть, оба обработчика в основном одинаковы
public class HasArranqueActivoHandler : AuthorizationHandler<HasArranqueActivoRequirement>
{
private readonly NoPaperContext _context;
public HasArranqueActivoHandler(NoPaperContext context)
{
_context = context;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasArranqueActivoRequirement requirement)
{
// Do something with _context
// Check if the requirement is fulfilled.
var registoId = Convert.ToInt32(context.User.FindFirst(c => c.Type == ClaimTypes.PrimarySid).Value);
var registo = _context.Registos.Find(registoId);
if (registo.IsArranqueActivo)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
public class HasArranqueInactivoHandler : AuthorizationHandler<HasArranqueInactivoRequirement>
{
private readonly NoPaperContext _context;
public HasArranqueInactivoHandler(NoPaperContext context)
{
_context = context;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasArranqueInactivoRequirement requirement)
{
// Do something with _context
// Check if the requirement is fulfilled.
var registoId = Convert.ToInt32(context.User.FindFirst(c => c.Type == ClaimTypes.PrimarySid).Value);
var registo = _context.Registos.Find(registoId);
if (!registo.IsArranqueActivo)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
На моемстраница у меня есть wrotten, и он не вызывает обработчик политики, и я продолжаю получать отказано в доступе.Почему?
[Authorize(AuthenticationSchemes = "ProductionAuth", Policy = "HasArranqueInactivo")]
РЕДАКТИРОВАТЬ
это весь запуск
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication()
.AddCookie("ProductionAuth", options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(1);
options.LoginPath = new PathString("/Production/Index");
options.LogoutPath = new PathString("/Production/Logout");
options.AccessDeniedPath = new PathString("/Production/AccessDenied/");
options.SlidingExpiration = true;
})
.AddCookie("AdministrationAuth", options =>
{
options.ExpireTimeSpan = TimeSpan.FromDays(1);
options.LoginPath = new PathString("/Administration/Index");
options.LogoutPath = new PathString("/Administration/Logout");
options.AccessDeniedPath = new PathString("/Administration/AccessDenied/");
options.SlidingExpiration = true;
});
services.AddAuthorization(options =>
{
options.AddPolicy("HasArranqueActivo", policy =>
policy.Requirements.Add(new HasArranqueActivoRequirement()
));
options.AddPolicy("HasArranqueInactivo", policy =>
policy.Requirements.Add(new HasArranqueInactivoRequirement()
));
});
services.AddSingleton<IFileProvider>(
new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/files")));
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.AllowAreas = true;
options.Conventions.AuthorizeAreaFolder("Administration", "/Account");
options.Conventions.AuthorizeAreaFolder("Production", "/Account");
})
.AddNToastNotifyToastr(new ToastrOptions()
{
ProgressBar = true,
TimeOut = 3000,
PositionClass = ToastPositions.TopFullWidth,
PreventDuplicates = true,
TapToDismiss = true
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddTransient<IAuthorizationHandler, HasArranqueActivoHandler>();
services.AddRouting(options =>
{
options.LowercaseUrls = true;
options.LowercaseQueryStrings = true;
});
services.AddDbContext<NoPaperContext>(options =>
{
//if(Environment.IsProduction())
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(
maxRetryCount: 2,
maxRetryDelay: TimeSpan.FromSeconds(1),
errorNumbersToAdd: null);
});
//else if(Environment.IsDevelopment())
//options.UseInMemoryDatabase(databaseName: "AbastecimentoDB");
});
services.AddHttpContextAccessor();
services.AddTransient<IComponenteService, ComponenteService>();
services.AddTransient<IReferenciaService, ReferenciaService>();
services.AddTransient<IRegistoService, RegistoService>();
services.AddTransient<IParagemService, ParagemService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseNToastNotify();
app.UseAuthentication();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}