ASP.NET Core 2.0 combining Cookies and Bearer Authorization for the same endpoint

后端 未结 5 471
梦如初夏
梦如初夏 2021-01-30 13:46

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 th

5条回答
  •  既然无缘
    2021-01-30 14:19

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

    For Documentation of my sources: registerAuthorizationHandlers

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

    Edit: 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();
    }
    

提交回复
热议问题