Невозможно получить доступ к клиентскому приложению с помощью сервера идентификации - PullRequest
0 голосов
/ 20 марта 2019

Я пытаюсь аутентифицировать клиентское приложение MVC, используя идентификационный сервер.

мое приложение имеет приложение mvc Identity server, приложение MVC, API

Я использую 4 области в клиентском приложении MVC (OpenId, электронная почта, профиль, office - office - пользовательский тип заявки).

Я использую этот код для создания сервера идентификации с приложением аутентификации mvc.

1 identity server run 

2 MVC application run 

3 Login link click using MVC application 

Изображение1

4 Login the identity server using TestUser details

Image2

5 after login success always display this screen (not show my all scope to check in client application)

Изображение3

Identity Server - (http://localhost:61632)

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.AddMvc();

            services.AddIdentityServer()
               .AddTestUsers(TestUsers.Users)
               .AddInMemoryClients(Config.GetClients())
               .AddInMemoryIdentityResources(Config.GetIdentityResources())
               .AddInMemoryApiResources(Config.GetApiResources());

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseIdentityServer();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

TestUser класс

 public class TestUsers
    {
        public static List<TestUser> Users = new List<TestUser>
        {
            new TestUser{SubjectId = "818727", Username = "Kasunjith", Password = "kasunjith", 
                Claims = 
                {
                    new Claim("office_Id","23"),
                    new Claim(JwtClaimTypes.Name, "Alice Smith"),
                    new Claim(JwtClaimTypes.GivenName, "Alice"),
                    new Claim(JwtClaimTypes.FamilyName, "Smith"),
                    new Claim(JwtClaimTypes.Email, "AliceSmith@email.com"),
                    new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                    new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
                    new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json)
                }
            },
            new TestUser{SubjectId = "88421113", Username = "bimal", Password = "bimal", 
                Claims = 
                {
                    new Claim("office_Id","24"),
                    new Claim(JwtClaimTypes.Name, "Bob Smith"),
                    new Claim(JwtClaimTypes.GivenName, "Bob"),
                    new Claim(JwtClaimTypes.FamilyName, "Smith"),
                    new Claim(JwtClaimTypes.Email, "BobSmith@email.com"),
                    new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                    new Claim(JwtClaimTypes.WebSite, "http://bob.com"),
                    new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServer4.IdentityServerConstants.ClaimValueTypes.Json),
                    new Claim("location", "somewhere")
                }
            }
        };
    }

Конфиг класс

 public class Config
    {
        public static IEnumerable<Client> GetClients()
        {
            return new Client[]
            {
                new Client
                {
                    ClientId ="mvc",
                    ClientName="MVC Demo",
                    AllowedGrantTypes = GrantTypes.Implicit,
                    RedirectUris ={ "http://localhost:62104/signin-oidc" },
                    AllowedScopes={ "openid","email", "profile","office"},
                    AllowRememberConsent = true,

                }

            };
        }

        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new IdentityResource[]
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Email(),
                new IdentityResources.Profile(),
                new IdentityResource
                {
                    Name="office",
                    DisplayName ="office details",
                    UserClaims = {"office_Id"}
                }


            };
        }


        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new ApiResource[]
            {

            };
        }
    }

Клиент - приложение Mvc (http://localhost:62104)

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.AddMvc();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
                //options.DefaultAuthenticateScheme = "Cookies";
            }).AddCookie("Cookies")
             .AddOpenIdConnect("oidc", options =>
             {

                 options.SignInScheme = "Cookies";
                 options.RequireHttpsMetadata = false;
                 options.Authority = "http://localhost:61632";
                 options.ClientId = "mvc";
                 options.ResponseType = "id_token";
                 //options.CallbackPath = new PathString("...")
                 //options.SignedOutCallbackPath = new PathString("...")
                 options.Scope.Add("openid");
                 options.Scope.Add("email");
                 options.Scope.Add("profile");
                 options.Scope.Add("office");




             });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();


            app.UseAuthentication();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }

1 Ответ

0 голосов
/ 21 марта 2019

Найдена проблема (это было сложно!)

Код работает просто отлично.Часть, которая не работает, отображает области в представлении Consent.Проблема сводится к этой строке:

Views / Consent / Index.cshtml

<partial name="_ScopeListItem" model="@scope" />

При этом используется Partial Tag Helper , введено в ASP.NET 2.1.

Проект, который вы связали в комментариях (ваш проект), использует ASP.NET 2.0, но QuickStart UI, который вы скопировали с IdentityServer , использует ASP.NET Core 2.1, поэтому в принципе они несовместимы,Чтобы исправить это, используйте соответствующий помощник по тегам для вашей версии или (я рекомендую) обновить до ASP.NET Core 2.2.Для этого вы можете:

Изменить файл проекта:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <!-- Upgrade the project to .NET Core 2.2-->
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="IdentityServer4" Version="2.3.2" />

    <!-- Change the ASP.NET Core from All to App. -->
    <PackageReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.2" />
  </ItemGroup>

</Project>

И Startup.cs

public IConfiguration Configuration { get; }
public IHostingEnvironment Environment { get; }

public Startup(IConfiguration configuration, IHostingEnvironment environment)
{
    Configuration = configuration;
    Environment = environment;
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_1);

    var builder = services.AddIdentityServer()
       .AddTestUsers(TestUsers.Users)
       .AddInMemoryClients(Config.GetClients())
       .AddInMemoryIdentityResources(Config.GetIdentityResources())
       .AddInMemoryApiResources(Config.GetApiResources());

    // without this you can't sign jwt tokens in dev. still need to configure for prod.
    if (Environment.IsDevelopment())
    {
        builder.AddDeveloperSigningCredential();
    }
    else
    {
        throw new Exception("need to configure key material");
    }

}

Так как вы в это, я бы также предложилОбновление приложения MVC (клиент).Я отправил PR в вашем репозитории GitHub, в котором указаны вышеупомянутые изменения, а также список областей действия / претензий после входа вашего пользователя.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...