Search code examples
restazureasp.net-identityopenid

Authenticated REST API for a mobile app and website on ASP.NET Core with OpenIdConnect


I have a pretty much boilerplate "ASP.NET Core Web Application (.NET Framework)" application, that should become a REST API, to be hosted on Azure, for use for a website & mobile app.

I want to equip it with token authentication through the headers, and I have chosen for the OpenIdConnect package.

I have copypasted the snippets from this page (https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server) into my template, and added the app.UseOAuthValidation() call, so the code looks like this:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddAuthentication();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseOAuthValidation();

    app.UseOpenIdConnectServer(options =>
        {
              //..... Copy-paste from the OpenIdConnect page

              OnValidateTokenRequest = context => { ... }
              OnHandleTokenRequest = context => { ... }
        });

    app.UseMvc();
}

I am able to get a token (POST to /connect/token).

If I add an [Authorize] to my ValuesController to GET and set the Authorization header with the token but I keep on getting a 401 Unauthorized. The code doesn't even break into the OnValidateTokenRequest or OnHandleTokenRequest methods.

What am I missing?


Solution

  • You are doing it kind of wrong.

    Let me explain shortly. Your REST API will not be the OpenIDConnect server. It should just authenticate a token given to it.

    This article looks pretty good: https://contos.io/protecting-a-net-core-api-with-azure-active-directory-59bbcd5b3429#.1w8djbaci This example uses Azure AD, but since you are hosting on Azure, I assume that would be a good option for you.

    In short, you need something like this in your API:

    app.UseJwtBearerAuthentication(new JwtBearerOptions
    {
        Authority = Configuration[“Authentication:AzureAd:AADInstance”] 
        + Configuration[“Authentication:AzureAd:TenantId”], 
        Audience = Configuration[“Authentication:AzureAD:ClientId”], 
        TokenValidationParameters = 
        new Microsoft.IdentityModel.Tokens.TokenValidationParameters 
          {
            ValidIssuer = 
            Configuration [“Authentication:AzureAd:AADInstance”] 
          + Configuration[“Authentication:AzureAd:TenantId”] + “/v2.0” }
    });