5

I'm working on an ASP.net Core 2.0 application which uses an IdentityServer4 token server for authentication. My application has Razor Pages, which I'd like to use Cookie authentication with, and it also has an API, which I'd like to use Bearer tokens with.

Here's the setup I have in my Startup.cs:

    public void ConfigureServices(IServiceCollection services) {
//...
        services.AddAuthentication(options => { options.DefaultChallengeScheme = "oidc"; })
            .AddIdentityServerAuthentication(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.Authority = Configuration["OpenIDConnect:Authority"];
                options.ApiName = Configuration["OpenIDConnect:ApiName"];
                options.JwtBearerEvents.OnChallenge += async context =>
                {
                    context.Response.StatusCode = StatusCodes.Status403Forbidden;
                    context.HandleResponse();
                };
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = "Cookies";
                options.Authority = Configuration["OpenIdConnect:Authority"];
                options.RequireHttpsMetadata = false;
                options.ClientId = Configuration["OpenIdConnect:ClientId"];
                options.SaveTokens = true;
                options.Scope.Add("role");
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                };
            });

        services.AddAuthorization(options =>
        {
            options.AddPolicy(Constants.Policies.ApiUserWithBearerToken,
                policy =>
                {
                    policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme);
                    policy.AuthenticationSchemes.Remove(CookieAuthenticationDefaults.AuthenticationScheme);
                    policy.AuthenticationSchemes.Remove("oidc");
                    policy.RequireClaim("MobileClient", "true");
                    policy.RequireClaim("ApiUser", "true");
                });
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    //…
    //…
    app.UseAuthentication();
}

And here's an API endpoint I'm trying to secure with a Bearer token:

[Route("api/[controller]"), Authorize(Policy = "ApiUserWithBearerToken", AuthenticationSchemes = "Bearer"), MobileAppController]
public class CatalogController : Controller
{
    // …
    [HttpGet("current")]
    public async Task<IActionResult> Current()
    {
        // …
    }        
}

My problem is that ASP.net seems to be completely ignoring my Bearer authentication scheme setup. If I request the current endpoint with a valid bearer token, it returns a redirect to IdentityServer asking me to sign in.

Here's the message log from Kestrel:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5001/api/Catalog/current
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[12]
      AuthenticationScheme: oidc was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action Pinball.Web.Controllers.CatalogController.Current (Catalog.Web) in 1185.1356ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 1871.9771ms 302

If I remove the default challenge scheme, then ASP.net just throws an exception saying it's required.

What am I missing here?

1
  • Did you manage to solve this issue? Jul 25, 2018 at 7:53

1 Answer 1

2

I had the same problem, and since I solved it I'm glad to offer my solution. When you add Identity Server by calling services.AddIdentityServer() cookie authentication is added by default as you can see here https://github.com/IdentityServer/IdentityServer4/blob/75b1a660c3cab2580112e6e0288f3f6bed8189f9/src/Configuration/DependencyInjection/IdentityServerServiceCollectionExtensions.cs

builder
   .AddRequiredPlatformServices()
   .AddCookieAuthentication() // <-- Cookie auth added
   .AddCoreServices()
   .AddDefaultEndpoints()
   .AddPluggableServices()
   .AddValidators()
   .AddResponseGenerators()
   .AddDefaultSecretParsers()
   .AddDefaultSecretValidators();

After that you add the Authentication with services.AddAuthentication() so at that point you don't need to be adding cookie authentication anymore since it has already been added. You only need to add IS authentication by adding following code:

services.AddAuthentication()
    .AddIdentityServerAuthentication(options =>
    {
        options.Authority = Configuration["Settings:Authentication:Authority"];
        options.RequireHttpsMetadata = !CurrentEnvironment.IsDevelopment();

        options.ApiName = Configuration["Settings:Authentication:ApiName"];
        options.ApiSecret = Configuration["Settings:Authentication:ApiSecret"];
     });

You also don't need .AddOpenIdConnect() method.

Now, keep in mind when you've done this, you have two authentication methods declared for serving your auth requests. First one is cookie(added by the IS) and the other one is JWT bearer added by calling .AddIdentityServerAuthentication(). Since the cookie was added first, it will also be called first when any request needs to be authenticated, therefore you need to specify which of the methods you would like to use at point of authorisation, which you did correctly by using :

[Route("api/[controller]"), Authorize(Policy = "ApiUserWithBearerToken", AuthenticationSchemes = "Bearer"), MobileAppController]

I personally use IS default but the result is the same:

[Route("api/[controller]"), Authorize(Policy = "ApiUserWithBearerToken", AuthenticationSchemes = IdentityServerAuthenticationDefaults.AuthenticationScheme), MobileAppController]

With this, you should have a working app that can serve both API requests and Razor pages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.