如何防止Cookie身份验证重定向到登录

时间:2019-06-04 15:57:10

标签: asp.net-core

我正在构建一个内部站点,该站点使用核心Web API作为后端,而angular作为前端。因为数据库和整个项目结构的编写方式,所以我有一种非常规的方式来授权用户。我正在获取Windows登录名(不使用身份或任何登录页面),然后将其与数据库中拥有的授权用户列表进行比较。我已经使授权处理程序正常工作,但是我一直在寻找一种方法来防止我的策略重定向到登录页面(将不存在)。我只想获取401状态代码,而不是重定向,因此可以使用Angular进行通知

我已经在google /堆栈溢出上进行了各种搜索,所有示例和解决方案都使用身份或令牌策略,我没有走这条路线,我只是使用了一个伪造的cookie auth来使我的授权策略生效

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddAutoMapper();
        services.AddScoped<IChecklistRepository, ChecklistRepository>();
        services.AddCors(o => o.AddPolicy("Angular", b=>
        {
            b.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
        }));
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
            opt =>
            {
                opt.LoginPath = null;
                opt.AccessDeniedPath = null;
               // Does not do anything 

            });

        services.AddDbContext<SWAT_UpdateChecklistsContext>(opt => opt.UseMySql(Configuration.GetConnectionString("conn")));
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(o =>
        {
            o.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        });


        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });

        services.AddAuthorization(opt =>
        {
            opt.AddPolicy("AccessUser", policy => {
                policy.Requirements.Add(new UserAccess());


                });

        });

        services.AddTransient<IAuthorizationHandler, AuthorizedUser>();
    }

1 个答案:

答案 0 :(得分:1)

我做了一些进一步的挖掘,认为我找到了答案,

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
            opt =>
            {

                opt.Events.OnRedirectToLogin = ctx =>
                {
                    ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    return Task.CompletedTask;
                };
                opt.Events.OnRedirectToAccessDenied = ctx =>
                {
                    ctx.Response.StatusCode = StatusCodes.Status403Forbidden;
                    return Task.CompletedTask;
                };

            });
相关问题