Search code examples
apiidentityserver4asp.net-core-3.1

Secure API .net core 3.1 (upgraded api from 2.2) with identityserver no longer works, is my middleware correct?


I have an API (.net core 2.2) protected and working fine with Identity server.

I need to upgrade this API to .net core 3.1. So I started fresh with a core 3.1 API project and added in the controllers, dbContext and the middleware... I have tried to match the middleware as close to the 2.2 as possible (which may be my problem) but I am receiving a 401 unauthorised on methods decorated with [Authorize] (without even declaring any roles or policies, just a simple Authorize). If I take off the [Authorize] this works fine... so here lies the problem.

I have tried to find examples of upgrading the API from 2.2 to 3.1 from a middleware IdentityServer point of view, but only able to find examples of upgrading IdentityServer itself (not a protected API) between these versions.

I have also analysed the User claims in the API method, which all look fine. This works fine on 2.2, so I think this must be to do with the middleware, but I'm not sure... can someone point me in the right direction please? Here is my startup file:

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using HMS.API.Services;
using HMS.Global.Repository;

namespace HMS.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            services.AddControllers();

            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            { 
                options.Authority = "https://????.???????.com"; // Removed for this post
                options.ApiName = "hmsapi";
                
            });

            services.AddDbContext<DbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("HMSConnection")));

            // Create policy
            services.AddAuthorization(authorisationOptions =>
            {
                authorisationOptions
                .AddPolicy(
                    "HMSADMINPOLICY",
                    policyBuilder =>
                    {
                        policyBuilder.RequireAuthenticatedUser();
                        policyBuilder.RequireClaim("role", "HMSADMIN");                        
                    });

                authorisationOptions
                .AddPolicy(
                    "HMSSTANDARDPOLICY",
                    policyBuilder =>
                    {
                        policyBuilder.RequireAuthenticatedUser();
                        policyBuilder.RequireClaim("role", "HMSSTANDARD", "HMSADMIN");
                    });
            });

            services.AddSingleton<IUserService, UserService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Solution

  • I would use Fiddler to debug the traffic to/from my client application and especially look at the claims that are actually returned from IdentityServer.

    If you are getting 401 not authorized when you just use [Authorize], then you are not really logged in. All users who are logged in should pass [Authorize].

    If you are also upgrading to IdentityServer4 v4.0x , then you need to add your ApiScopes as well (New feature in v4.x)