我创建了一个新的ASP.NET Core Web应用程序项目在VS17中使用"Web应用程序(模型视图控制器)"模板和".NET Framework"+"ASP.NET Core 2"作为配置.身份验证配置设置为"个人用户帐户".

我有以下示例端点:

[Produces("application/json")]
[Route("api/price")]
[Authorize(Roles = "PriceViwer", AuthenticationSchemes = "Cookies,Bearer")]
public class PriceController : Controller
{

    public IActionResult Get()
    {
        return Ok(new Dictionary<string, string> { {"Galleon/Pound",
                                                   "999.999" } );
    }
}

"Cookies,Bearer"是通过连接CookieAuthenticationDefaults.AuthenticationSchemeJwtBearerDefaults.AuthenticationScheme得到的.

目标是能够配置端点的授权,以便可以使用令牌和Cookie身份验证方法访问它.

以下是我在启动时的身份验证设置.反恐精英:

    services.AddAuthentication()
        .AddCookie(cfg => { cfg.SlidingExpiration = true;})
        .AddJwtBearer(cfg => {
            cfg.RequireHttpsMetadata = false;
            cfg.SaveToken = true;
            cfg.TokenValidationParameters = new TokenValidationParameters() {
                                                    ValidIssuer = Configuration["Tokens:Issuer"],
                                                    ValidAudience = Configuration["Tokens:Issuer"],
                                                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                                                };
        });

So, when I try to access the endpoint using a browser, I get the 401 response with a blank html page.
I get the 401 response with a blank html page.

然后我登录,当我再次try 访问端点时,我得到相同的响应.

Then, I try to access the endpoint by specifying the bearer token. And that returns the desired result with the 200 response.
And that returns the desired result with the 200 response.

因此,如果我删除[Authorize(AuthenticationSchemes = "Cookies,Bearer")],情况就相反了——cookie身份验证工作并返回200,但是上面使用的相同的承载令牌方法不会给出任何结果,只会重定向到默认的AspIdentity登录页面.

我可以看到两个可能的问题:

1) ASP.NET Core不允许"组合"身份验证.

请告知.非常感谢.

推荐答案

我认为您不需要将AuthenticationScheme设置为控制器.只需在以下配置服务中使用经过身份验证的用户:

// requires: using Microsoft.AspNetCore.Authorization;
//           using Microsoft.AspNetCore.Mvc.Authorization;
services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});

关于我的资料来源的文件:registerAuthorizationHandlers

对于该部分,无论scheme密钥是否无效,都可以使用插值字符串来使用正确的密钥:

[Authorize(AuthenticationSchemes = $"{CookieAuthenticationDefaults.AuthenticationScheme},{JwtBearerDefaults.AuthenticationScheme}")]

编辑:

//private method
private IActionResult GetThingPrivate()
{
   //your Code here
}

//Jwt-Method
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[HttpGet("bearer")]
public IActionResult GetByBearer()
{
   return GetThingsPrivate();
}

 //Cookie-Method
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
[HttpGet("cookie")]
public IActionResult GetByCookie()
{
   return GetThingsPrivate();
}

Asp.net相关问答推荐

Azure DevOps 构建管道正在发布旧的/缓存的构建工件

设置主键时KeyAttribute属性不起作用

在 Windows Server 2008 IIS7 上的 ASP.NET 中写入事件日志(log)

为什么 Web 架构应该是松耦合的?

ASP.NET Core 1.0 ConfigurationBuilder().AddJsonFile("appsettings.json");找不到文件

iframe.readyState 在 chrome 中不起作用

如何将配置转换应用于外部配置文件

OnCheckedChanged 事件未触发

如何判断一个IP地址是否是私有的?

Web.config 导致被组策略阻止错误

Devexpress 或 Telerik Controls 比较

在生产中使用 LocalDb 是否正常?

如何使用 ASP.NET 和 jQuery 返回 JSON

如何忽略身份框架的魔力,只使用 OWIN 身份验证中间件来获取我寻求的声明?

如何在 ASP.NET 中通过 LAN 访问您的网站

使用 ASP.NET 进行重定向后获取

MVC3 和实体框架

GridView 按代码隐藏列

如何在服务器控件属性中使用 ASP.NET <%= 标签?

ModelClientValidationRule 冲突