0
votes

im facing a problem trying to implement simple token authentication on .net core 1.0.1, ive followed a simple tutorial that i fond here: http://kevinchalet.com/2017/01/30/implementing-simple-token-authentication-in-aspnet-core-with-openiddict/

When i try to send a request to http://localhost:51863/connect/token?grant_type=password&username=alice%40wonderland.com&password=P%40ssw0rd i got the response : invalid_request","error_description":"The specified HTTP method is not valid.

my startup.cs:

 services.AddDbContext<AssistDbContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("AssistContext"));
        });
        services.AddScoped<AssistDbContext, AssistDbContext>();

        services.AddDbContext<DbContext>(options =>
        {
            // Configure the context to use an in-memory store.
            options.UseInMemoryDatabase();
            // Register the entity sets needed by OpenIddict.
            // Note: use the generic overload if you need
            // to replace the default OpenIddict entities.
            options.UseOpenIddict();
        });

        services.AddOpenIddict(options =>
        {
            // Register the Entity Framework stores.
            options.AddEntityFrameworkCoreStores<DbContext>();
            // Register the ASP.NET Core MVC binder used by OpenIddict.
            // Note: if you don't call this method, you won't be able to
            // bind OpenIdConnectRequest or OpenIdConnectResponse parameters.
            options.AddMvcBinders();
            // Enable the token endpoint.
            options.EnableTokenEndpoint("/api/authorization/token");
            // Enable the password flow.
            options.AllowPasswordFlow();
            // During development, you can disable the HTTPS requirement.
            options.DisableHttpsRequirement();
        });

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
           loggerFactory.AddConsole(Configuration.GetSection("Logging"));
           loggerFactory.AddDebug();

           app.UseApplicationInsightsRequestTelemetry();

           app.UseApplicationInsightsExceptionTelemetry();

           // Register the validation middleware, that is used to decrypt
           // the access tokens and populate the HttpContext.User property.
           app.UseOAuthValidation();
           // Register the OpenIddict middleware.
           app.UseOpenIddict();
           app.UseMvcWithDefaultRoute();

        }

UPDATE Testing with Postman returns 404:

enter image description here

Logs:

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST http://localhost:51863/api/Authorization application/x-www-form-urlencoded 49 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Users\consultoria.nuget\packages\AspNet.Security.OpenIdConnect.Extensions\1.0.2\lib\netstandard1.4\AspNet.Security.OpenIdConnect.Extensions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Users\consultoria.nuget\packages\Microsoft.AspNetCore.WebUtilities\1.1.0-preview1-final\lib\netstandard1.3\Microsoft.AspNetCore.WebUtilities.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerMiddleware:Information: The token request was successfully extracted from the HTTP request: { "grant_type": "password", "username": "teste", "password": "[removed for security reasons]" }. 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Users\consultoria.nuget\packages\Microsoft.EntityFrameworkCore.InMemory\1.0.1\lib\netstandard1.3\Microsoft.EntityFrameworkCore.InMemory.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Users\consultoria.nuget\packages\Remotion.Linq\2.1.1\lib\netstandard1.0\Remotion.Linq.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Users\consultoria.nuget\packages\System.Interactive.Async\3.0.0\lib\netstandard1.0\System.Interactive.Async.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.0.1\System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.0.1\System.Reflection.Metadata.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.0.1\System.IO.MemoryMappedFiles.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. 'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\1.0.1\System.IO.UnmanagedMemoryStream.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled. Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware:Error: An unhandled exception has occurred: Method 'get_CurrentTransaction' in type 'Microsoft.EntityFrameworkCore.Storage.Internal.InMemoryTransactionManager' from assembly 'Microsoft.EntityFrameworkCore.InMemory, Version=1.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' does not have an implementation.

System.TypeLoadException: Method 'get_CurrentTransaction' in type 'Microsoft.EntityFrameworkCore.Storage.Internal.InMemoryTransactionManager' from assembly 'Microsoft.EntityFrameworkCore.InMemory, Version=1.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60' does not have an implementation. at Microsoft.Extensions.DependencyInjection.InMemoryServiceCollectionExtensions.AddEntityFrameworkInMemoryDatabase(IServiceCollection services) at Microsoft.EntityFrameworkCore.Internal.ServiceProviderCache.<>c__DisplayClass4_1.b__2(Int64 k) at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory) at Microsoft.EntityFrameworkCore.DbContext..ctor(DbContextOptions options) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.b__0(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at OpenIddict.OpenIddictProvider4.<ValidateTokenRequest>d__8.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerHandler.<InvokeTokenEndpointAsync>d__17.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at AspNet.Security.OpenIdConnect.Server.OpenIdConnectServerHandler.<HandleRequestAsync>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware1.d__18.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware1.<Invoke>d__18.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware1.d__18.MoveNext() --- End of stack trace from previous location where exception was thrown --- at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware`1.d__18.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.d__6.MoveNext() Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Request","time":"2017-10-27T14:41:33.6130254Z","tags":{"ai.operation.id":"VBvjL4hwyqs=","ai.user.userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36","ai.internal.sdkVersion":"aspnet5c:1.0.0","ai.operation.name":"POST /api/Authorization","ai.device.roleInstance":"CPD200"},"data":{"baseType":"RequestData","baseData":{"ver":2,"id":"VBvjL4hwyqs=","name":"POST /api/Authorization","startTime":"2017-10-27T14:41:33.6130254+00:00","duration":"00:00:00.4732983","success":false,"responseCode":"404","url":"http://localhost:51863/api/Authorization","httpMethod":"POST","properties":{"DeveloperMode":"true"}}}} Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 490.1896ms 404

2

2 Answers

2
votes

The error message is extremely clear: you're using a wrong HTTP method (probably GET as I can see the query string parameters attached to the URI).

Use POST as required by the OAuth2 specification and it should work.

0
votes

Looks like following Authentication statement is missing from the code snippet

services.AddAuthentication(options =>
{
    options.DefaultScheme = OAuthValidationDefaults.AuthenticationScheme;
});