How To Implementing simple token authentication in ASP.NET Core with OpenIddict

How To Implementing simple token authentication in ASP.NET Core with OpenIddict | Best and cheap ASP.NET Core 1.0 hosting. Good news! While the first OpenIddict alpha bits were tied to Identity, the two have been completely decoupled as part of OpenIddict beta1 and beta2. Concretely, this means you can now use OpenIddict with your own authentication method or your own membership stack.

Get started

Register the aspnet-contrib feed

Before coding, you’ll have to register the aspnet-contrib MyGet feed, where the preliminary OpenIddict beta bits are currently hosted. For that, create a new NuGet.config at the root of your solution:

Update your project.json to reference the OpenIddict packages

For this demo, you’ll need to reference 4 packages:

  • AspNet.Security.OAuth.Validation, that provides the authentication middleware needed to validate the access tokens issued by OpenIddict.
  • OpenIddict, that references the OpenID Connect server middleware and provides the logic required to validate token requests.
  • OpenIddict.EntityFrameworkCore, that contains the default EntityFramework stores.
  • OpenIddict.Mvc, that provides an ASP.NET Core MVC binder allowing to use OpenIdConnectRequest as an action parameter.

Add OpenIddict in the ASP.NET Core application

Register the OpenIddict services in the dependency injection container

Register OpenIddict and the validation middleware in the ASP.NET Core pipeline

Make sure to always register the validation middleware very early in your pipeline: if the validation middleware is not at the right place, requests won’t be correctly authenticated when reaching the next middleware (e.g MVC).

The same remark applies to OpenIddict, that must be inserted before MVC to validate token requests before they reach your own code. If you don’t register it correctly, an exception will be thrown at runtime.

Create your own token authentication controller

Create an API controller

Test your ASP.NET Core application

Retrieve an access token from your authentication controller

To retrieve an access token, send a POST request to /connect/token with the grant_type=password parameter and the user credentials:


If the credentials are valid, you’ll get a JSON response containing the access token:

Query your API controller using a bearer token

To send an authenticated request, simply attach the bearer token to the Authorization header using the following syntax: Authorization: Bearer [your bearer token] (without the square brackets)


If the access token is valid, you’ll get a JSON payload containing the user details returned by the API: