Search code examples
c#identityserver4webapi

WebApi server only accesses IdentityServer once after it starts


Good day.

  1. I request an access token with IdentityServer
  2. I am accessing my API after starting the webapi server.
  3. After that, using the current access token, I can access my api, even if the IdentityServer is turned off.

My question: Is this the correct logic of work? Shouldn't the IdentityServer be called on every call to my api and check the access token?

If not, how can I refuse the access token if my user's credentials have been changed and I need to renew the token?

Startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers().RequireAuthorization("ApiScope");
                //.RequireAuthorization("AdminSecure");
            });
        }

public void ConfigureServices(IServiceCollection services)
        {
           services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = Configuration.GetValue<string>("IdentityServerUrl");
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = false
                    };
                });
            services.AddAuthorization(options =>
            {
                options.AddPolicy("ApiScope", policy =>
                policy.RequireClaim("client_id", "secret"));

                options.AddPolicy("UserSecure", policy =>
                policy.RequireClaim("roleType", "userCode"));

                options.AddPolicy("AdminSecure", policy =>
                policy.RequireClaim("roleType", "adminCode"));
            });
}

Solution

  • This is correct behavior, that your API can work offline from the IdentityServer. The API only needs to download the signing keys from IdentityServer and the API will by default cache them for 24h so that it can verify that they are valid.

    The problem you describe is solved by using short lived access tokens, like 1-10 minutes? and then use refresh tokens in the client to renew the tokens.

    Alternatively your API can manually ask the token introspection endpoint to check if an access token is still valid.