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

后端 未结 5 473
梦如初夏
梦如初夏 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:37

    I had a scenario where I need to use Bearer or Cookie only for file download api alone. So following solution works for me.

    Configure services as shown below.

    services.AddAuthentication(options =>
    {
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddJwtBearer(options =>
    {
        options.Authority = gatewayUrl;
    })
    .AddOpenIdConnect(options =>
    {
        // Setting default signin scheme for openidconnect makes it to force 
        // use cookies handler for signin 
        // because jwthandler doesnt have SigninAsync implemented
        options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.Authority = "https://youridp.com";
        options.ClientId = "yourclientid";
        options.CallbackPath = "/signin-oidc";
        options.ResponseType = OpenIdConnectResponseType.Code;
    });
    

    Then configure your controller as shown below.

    [HttpGet]
    [Authorize(AuthenticationSchemes = "Bearer,OpenIdConnect")]
    public async Task Download([FromQuery(Name = "token")] string token)
    {
        ///your code goes here.
        ///My file download api will work with both bearer or automatically authenticate with cookies using OpenidConnect.
    }
    

提交回复
热议问题