ASP.NET Core 2.0结合了Cookie和承载授权给同一终结点 [英] ASP.NET Core 2.0 combining Cookies and Bearer Authorization for the same endpoint

查看:201
本文介绍了ASP.NET Core 2.0结合了Cookie和承载授权给同一终结点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've created a new ASP.NET Core Web Application project in VS17 using the "Web Application (Model-View-Controller)" template and ".Net Framework" + "ASP.NET Core 2" as the configuration. The authentication config is set to "Individual User Accounts".

我有以下示例端点:

[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串联而得出的.

"Cookies,Bearer" is derived by concatenating CookieAuthenticationDefaults.AuthenticationScheme and JwtBearerDefaults.AuthenticationScheme.

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

The objective is to be able to configure the authorization for the end point so that it's possible access it using both the token and cookie authentication methods.

这是我在Startup.cs中进行身份验证的设置:

Here is the setup I have for Authentication in my Startup.cs:

    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"]))
                                                };
        });

因此,当我尝试使用浏览器访问端点时,我收到了带有空白HTML页面的401响应.

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

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

Then I login and when I try to access the endpoint again, I get the same response.

然后,我尝试通过指定承载令牌来访问端点.并以200响应返回期望的结果.

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

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

So then, if I remove [Authorize(AuthenticationSchemes = "Cookies,Bearer")], the situation becomes the opposite - cookie authentication works and returns 200, however the same bearer token method as used above doesn't give any results and just redirect to the default AspIdentity login page.

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

I can see two possible problems here:

1)ASP.NET Core不允许组合"身份验证. 2)'Cookies'不是有效的架构名称.但是,什么才是合适的呢?

1) ASP.NET Core doesn't allow 'combined' authentication. 2) 'Cookies' is not a valid schema name. But then what is the right one to use?

请告知.谢谢.

推荐答案

我认为您不需要将AuthenticationScheme设置为Controller.只需在ConfigureServices中使用经过身份验证的用户,如下所示:

I think you don't need to set the AuthenticationScheme to your Controller. Just use Authenticated user in ConfigureServices like this:

// 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

For Documentation of my sources: registerAuthorizationHandlers

对于部分而言,无论scheme-Key是否无效,您都可以使用插值字符串来使用右键:

For the part, whether the scheme-Key wasn't valid, you could use an interpolated string, to use the right keys:

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

我做了进一步的研究,得出以下结论: 不可能用两个Schemes Or-Like来授权一个方法,但是您可以使用两个公共方法来调用私有方法,如下所示:

I did further research and came to following conclusion: It's not possible to authorize a method with two Schemes Or-Like, but you can use two public methods, to call a private method like this:

//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 Core 2.0结合了Cookie和承载授权给同一终结点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆