我创建了一个新的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相关问答推荐

是否可以发布 ASP.NET 5 应用程序以使目标机器不需要安装 DNX?

您如何处理多个环境的多个 web.config 文件?

在 lambda 表达式中否定 Func

IIS 中的嵌套 ASP.NET应用程序继承父配置值?

ASP.NET 如何将控件呈现为 HTML?

获取没有主机的 url 部分

System.Net.Http 版本冲突导致构建警告

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

用于链接字符串中的 url 的 C# 代码

在上下文中找不到 owin.Environment 项

如何在 Visual Studio 2017 中使用 NPM 并安装包?

等价于 ASP.NET Core 中的 Html.RenderAction

如何验证用户在 CheckBoxList 中 Select 了至少一个复选框?

ASP.NET MVC 2.0 JsonRequestBehavior 全局设置

具有自定义报告创建能力的最佳 ASP.NET 报告引擎

在c#中显示带有换行符的标签文本

如何使用 jquery 设置单选按钮 Select 的值

使用 NLog 在 ASP.NET Web API 2.1 中进行全局异常处理?

以编程方式滚动到锚标记

如何在 ASP.NET 响应中传递大文件?