ASP.Net Core 2.0 Web API中的Cookie身份验证

3

我正在尝试在ASP.Net Core 2.0 Web API中使用基于cookie的身份验证,并尝试使用以下代码激活它。登录页面托管在与应用程序托管不同的域中。我已将[Authorize]属性添加到控制器中。

在启动时,我可以看到调试器中调用了服务代码。

我的期望是当我的Web客户端使用Web API服务时,中间件将检测到标头没有cookie并将重定向客户端到登录页面。然而,我可以自由地调用控制器而不会被重定向。

    public void ConfigureServices(IServiceCollection services)
    {
            services.AddCors(options => options.AddPolicy("AllowAll",
            builder => builder.SetIsOriginAllowed(s => true)
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials()));

        services.TryAddTransient<CorsAuthorizationFilter, CorsAuthorizationFilter>();

        services.AddSwaggerGen(c =>
        {
            c.OperationFilter<FileOperationFilter>();
            c.SwaggerDoc("v1", new Info
            {
                Title = "Collateral Management API",
                Version = "v1"
            });
        });

        services.AddMvcCore(options =>
            {

                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddApiExplorer()
            .AddJsonFormatters(s => s.NullValueHandling = NullValueHandling.Ignore);

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(auth =>
            {
                auth.Cookie.Domain = "xxx.com";
                auth.Cookie.Name = "xxx";
                auth.LoginPath = "/signin";
                auth.AccessDeniedPath = "/signin";
            });

        services.AddAuthorization(auth =>
        {
            auth.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
        });
//...
}

并且以后...

app.UseAuthentication()

你已经配置了授权吗?只有在后续的授权中间件拒绝调用时,LoginPath 才会被使用。 - Pace
确保在 app.UseMvc 之前使用 app.UseAuthentication。如果在本地主机上进行测试,则省略域名。还可以尝试将 cookie 名称与身份验证方案相同。 - Joe Audette
@Pace,您能否详细说明一下您所说的配置授权是什么意思 - 根据您的评论,我也尝试了[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)],但这也没有起作用。 - Anand
我在回答中详细阐述了,因为这对于评论来说有点太多了。 - Pace
已经解决了吗?如果没有,请添加您的中间件代码和控制器代码。您是否在控制器构造函数中使用IHttpContextAccessor来访问您的cookie?如果没有,您需要添加它。 - Soleil
1个回答

5
尝试添加以下内容:
services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
});

services.AddMvc() 之后,
编辑:
考虑尝试以您添加 MVC 的方式:
// requires: using Microsoft.AspNetCore.Authorization;
//           using Microsoft.AspNetCore.Mvc.Authorization;
services.AddMvcCore(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});

AddMvcCore 默认不添加授权服务。您还需要执行 AddMvcCore(...).AddAuthorization()


添加了其他可尝试的内容。 - Pace
1
现在在调用API时,我遇到了异常No service for type 'Microsoft.AspNetCore.Authorization.Policy.IPolicyEvaluator' has been registered. 我编辑了我的问题,在ConfigureServices中提供了完整的相关代码。非常感谢您继续协助我。 - Anand
4
我没意识到 AddMvcCore 默认不会添加授权服务。你需要进行 AddMvcCore(...).AddAuthorization() 的操作。 - Pace
谢谢 - 异常已经消失了 - 但是API仍然没有受到保护。像以前一样正常返回数据。我在控制器类上使用[Authorize]属性。 - Anand
1
AddMvcCore(...).AddAuthorization() is what I needed with the policy being configured in the AddMvcCore builder method, not the AddAuthorization - Bronumski
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接