0

I am building a REST API using OAuth Bearer tokens as my method of authentication. So, I attempted to add an authorization policy so that I could do something like [Authorize("Bearer")]. However, when I go to test my new authorization policy, an exception is thrown stating

The following authentication scheme was not accepted: Bearer

I've tried multiple things in an attempt to stop this exception from being thrown, but I haven't had any luck. My Startup class can be found at https://gist.github.com/mw2nukeboy/4b6cc7d348ac60336b03.

Alex Justi
  • 167
  • 4
  • 13

1 Answers1

2

Update: in recent betas, configuring security options from ConfigureServices is no longer possible (except for Identity). You now need to directly configure the JWT options when calling app.UseJwtBearerAuthentication():

public void Configure(IApplicationBuilder app) {
    app.UseJwtBearerAuthentication(options => {
        // Configure the JWT options here.
    });
}

You forgot to add the OAuth2 bearer authentication middleware in your pipeline:

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    app.UseStaticFiles();

    app.UseOAuthBearerAuthentication();

    app.UseIdentity();

    app.UseMvc(routes => {
        routes.MapRoute(
            name: "default",
            template: "api/{controller}/{action}/{id?}",
            defaults: new {
                controller = "Home",
                action = "Index"

            });
    });
}

You're also not using the recommended approach to register the settings used by the OAuth2 bearer middleware:

public void ConfigureServices(IServiceCollection services) {
    // Not recommended approach.
    services.AddInstance(new OAuthBearerAuthenticationOptions { });

    // Recommended approach.
    services.ConfigureOAuthBearerAuthentication(options => {
        // Configure the options used by the OAuth2 bearer middleware.
    });
}
Kévin Chalet
  • 39,509
  • 7
  • 121
  • 131
  • Now, it can't resolve the OAuthBearerAuthentication options service – Alex Justi Jul 09 '15 at 16:18
  • `ConfigureOAuthBearerAuthentication` is in the `Microsoft.Framework.DependencyInjection` namespace. – Kévin Chalet Jul 09 '15 at 16:21
  • Note that you can also directly configure middleware options in the `app.UseOAuthBearerAuthentication(options => { ... })` call. – Kévin Chalet Jul 09 '15 at 16:23
  • 1
    I cannot resolve OAuthBearerAuthentication, IApplicationBuider doesn't contain it. The namespace Microsoft.Extensions.DependencyInjection as well. – Whistler Dec 15 '15 at 17:11
  • If you're using recent builds, it's not surprising as this answer was written in July: app.UseOAuthBearerAuthentication() is now app.UseJwtBearerAuthentication() (you can find it in the Microsoft.AspNet.Authentication.JwtBearer package) and the Microsoft.Framework namespace is now Microsoft.Extensions. I'll update my answer. – Kévin Chalet Dec 15 '15 at 17:25