6

Я получаю следующую ошибку при обращении к моему приложению Identity Server из моего клиентского приложения Javascript.Получение справки Проверка ошибки в Identity Server 4 с использованием JavaScript-клиента в ядре asp.net

неудачу: IdentityServer4.Validation.ScopeValidator [0] Invalid область применения:

OpenID

Я уверен, что я добавить объем в моем приложении идентификации сервера. Ниже мой код.

IdentityServer Применение (хост) Config.cs

public class Config 
{ 
    public static IEnumerable<ApiResource> GetApiResources() 
    { 
     return new List<ApiResource> 
     { 
      new ApiResource("api1","My API") 
     }; 
    } 

    public static IEnumerable<Client> GetClients() 
    { 
     return new List<Client> 
     { 
      new Client 
      { 
       ClientId = "js", 
       ClientName = "javaScript Client", 
       AllowedGrantTypes = GrantTypes.Implicit, 
       AllowAccessTokensViaBrowser = true, 
       RedirectUris = { "http://localhost:5003/callback.html" }, 
       PostLogoutRedirectUris = { "http://localhost:5003/index.html" }, 
       AllowedCorsOrigins = { "http://localhost:5003" }, 
       AllowedScopes = 
        { 
         IdentityServerConstants.StandardScopes.OpenId, 
         IdentityServerConstants.StandardScopes.Profile, 
         "api1" 
        } 
      } 
     }; 
    } 
} 

Startup.cs

public class Startup 
{ 
    // This method gets called by the runtime. Use this method to add services to the container. 
    // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 
    public void ConfigureServices(IServiceCollection services) 
    { 

     services.AddIdentityServer() 
      .AddTemporarySigningCredential() 
      .AddInMemoryApiResources(Config.GetApiResources()) 
      .AddInMemoryClients(Config.GetClients()); 
    } 

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     loggerFactory.AddConsole(); 

     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
      app.UseIdentityServer(); 
     } 

     app.Run(async (context) => 
     { 
      await context.Response.WriteAsync("Hello World!"); 
     }); 
    } 
} 

Web API Startup.cs

public class Startup 
{ 
    public Startup(IHostingEnvironment env) 
    { 
     var builder = new ConfigurationBuilder() 
      .SetBasePath(env.ContentRootPath) 
      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 
      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); 

     if (env.IsEnvironment("Development")) 
     { 
      // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately. 
      builder.AddApplicationInsightsSettings(developerMode: true); 
     } 

     builder.AddEnvironmentVariables(); 
     Configuration = builder.Build(); 
    } 

    public IConfigurationRoot Configuration { get; } 

    // This method gets called by the runtime. Use this method to add services to the container 
    public void ConfigureServices(IServiceCollection services) 
    { 
     // Add framework services. 
     services.AddApplicationInsightsTelemetry(Configuration); 

     services.AddCors(option => 
     { 
      option.AddPolicy("dafault", policy => 
      { 
       policy.WithOrigins("http://localhost:5003") 
         .AllowAnyHeader() 
         .AllowAnyMethod(); 
      }); 
     }); 
     services.AddMvcCore() 
       .AddAuthorization() 
       .AddJsonFormatters(); 
    } 

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
     loggerFactory.AddDebug(); 

     //this uses the policy called "default" 
     app.UseCors("default"); 

     app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions 
     { 
      Authority = "http://localhost:5000", 
      AllowedScopes = { "api1" }, 
      RequireHttpsMetadata = false 
     }); 

     app.UseApplicationInsightsRequestTelemetry(); 

     app.UseApplicationInsightsExceptionTelemetry(); 

     app.UseMvc(); 
    } 
} 
+0

им встретив та же ошибка, когда в документации содержится один и тот же образец. тебе повезло? – alessalessio

ответ

17

В то время как ваш клиент (приложение) конфигурируется или может запросить ресурс OpenId (или сферы), сервер идентичности не настроен для ресурса идентичности OpenID

Вы должны добавить его в качестве ресурса идентичности, аналогичной как его сделать here и иметь метод, который возвращает все ваши ресурсы идентификации, которые вы хотите использовать, как и сделанные here.

Короче добавить новый метод к вашему Config.cs, который выглядит следующим образом:

public static List<IdentityResource> GetIdentityResources() 
{ 
    return new List<IdentityResource> 
    { 
     new IdentityResources.OpenId() 
     new IdentityResources.Profile() // <-- usefull 
    } 
} 

а затем в identityservers контейнера службы добавить конфигурацию ресурсов идентичности, как это:

services.AddIdentityServer() 
    .AddTemporarySigningCredential() 
    .AddInMemoryApiResources(Config.GetApiResources()) 
    .AddInMemoryClients(Config.GetClients()); 
    .AddInMemoryIdentityResources(Config.GetIdentityResources()) // <-- adding identity resources/scopes 
+0

Его работа сейчас, но теперь его показ Показывать логин: Пользователь не аутентифицирован – maxspan

+0

Журналы - ваш друг, ваша консольная регистрация на уровне трассировки? – Lutando

+0

да. Он показывает IdentityServer4.ResponseHandling.AuthorizeInteractionResponseGenerator [0] Пользователь не аутентифицирован. Как аутентифицировать пользователя – maxspan