Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 1.0 OAuth Server using Openiddict

I would like to use Openiddict OAuth to protect api endpoints in my ASP.NET Core 1.0 Web Application. The api endpoints will be called by a phone app and users must login with username and password.

The flow goes like this:

  • User can register and login via web application: https://www.domain.com
  • User install phone app, and they can login and register using the phone app. Login, registration and data access is done via api endpoints: Example: https://www.domain.com/api/service/getsomedata

How can I configure Openiddict OAuth so I can protect the API endpoints using OAuth?

like image 514
user2818430 Avatar asked Jul 18 '16 07:07

user2818430


1 Answers

How can I configure Openiddict OAuth so I can protect the API endpoints using OAuth?

Your scenario sounds like a good candidate for the simple "resource owner password credentials" grant, which is basically the OAuth2 equivalent of basic or forms authentication.

Here's what I'd recommend:

Create a new AccountController/RegistrationController API controller responsible of creating new accounts:

Since the user account doesn't exist at this stage, you can't use token authentication here (just like the default AccountController.Register template cannot require cookies authentication before the user is registered).

Configure OpenIddict to enable the token endpoint and allow the resource owner password credentials grant:

services.AddOpenIddict<ApplicationDbContext>()
    // Disable the HTTPS requirement during development.
    .DisableHttpsRequirement()

    // Enable the token endpoint, required to use
    // the resource owner password credentials grant.
    .EnableTokenEndpoint("/connect/token")

    // Enable the password and the refresh token flows.
    .AllowPasswordFlow()
    .AllowRefreshTokenFlow();

Use the OAuth2 validation middleware to protect your APIs:

To enable token authentication, reference AspNet.Security.OAuth.Validation 1.0.0-alpha2-final package and add app.UseOAuthValidation() before app.UseMvc(). To make authentication mandatory, simply use the [Authorize] attribute like you'd do with cookies authentication.

Don't hesitate to play with this sample. It doesn't use a mobile app for the client-side part, but you should easily understand how it works.

For more information, you can also read this blog post, written by Mike Rousos for the Microsoft .NET Web Development and Tools blog: Bearer Token Authentication in ASP.NET Core

like image 181
Kévin Chalet Avatar answered Sep 24 '22 09:09

Kévin Chalet