Search code examples
identityserver4openid-connect

How to combine AddOpenIdConnect() and AddIdentityServerAuthentication() in one resource server?


Can somebody help me with my current configuration for protecting our server using Identity Server 4, currently I'm using package IdentityServer4 2.3.0. I found that when I hit one of my api with a valid token, it always return 401 Unauthorized or 302 Found. My comment on listing below show my problem:

services
   .AddAuthentication()
   .AddOpenIdConnect(
      "oidc",
      "OpenID Connect",
      x =>
      {
         x.Authority = "https://localhost:44378"; // Try to set breakpoint here, it hitted.
         x.SignInScheme = "Cookies";

         x.ClientId = "myclient;
         x.SaveTokens = true;
         x.GetClaimsFromUserInfoEndpoint = true;

         x.TokenValidationParameters = new TokenValidationParameters
         {
            NameClaimType = "name",
            RoleClaimType = "role"
         };
      })
   .AddIdentityServerAuthentication(
      "Bearer",
      x =>
      {
         x.Authority = "https://localhost:44378"; // Try to set breakpoint here, not hitted.
         x.ApiName = "api1";
         x.ApiSecret = "apisecret";
         x.RequireHttpsMetadata = true;
      })
   ;

Solution

  • Here's an example of how I do it to get the Hybrid flow working:

            services
                .AddAuthentication(
                    (options) =>
                    {
                        options.DefaultScheme = "Cookies";
                        options.DefaultChallengeScheme = "oidc";
                    })
                .AddCookie(
                    (options) =>
                    {
                        options.AccessDeniedPath = new PathString("/home/accessdenied");
                    })
                .AddOpenIdConnect(
                    "oidc",
                    (options) =>
                    {
                        options.SignInScheme = "Cookies";
                        options.Authority = applicationConfiguration.IdentityServerBaseUri;
                        options.RequireHttpsMetadata = false;
                        options.ClientId = "<id>";
                        options.ClientSecret = "<secret>";
                        options.ResponseType = "code id_token";
                        options.SaveTokens = true;
                        options.GetClaimsFromUserInfoEndpoint = true;
                        options.Scope.Add("lithium-datalookup-vatnumber");
                        options.Scope.Add("offline_access");
                        options.Scope.Add("profile");
                        options.Scope.Add("email");
                        options.Scope.Add("subscription");
                    });