1

У меня есть работающий IdentityServer и MVC Client в отдельных проектах, у меня также есть претензии, хранящиеся в ролях в моих идентификационных таблицах asp.net, это мой код данных семени для эти, которые затем назначаются пользователи:Идентификатор IdentityServer4 и .net Идентификатор ядра - Передача/получение заявок

if (await _roleManager.FindByNameAsync("Trainer") == null) 
     { 
      //Add Traininer Role 
      var trainerRole = new IdentityRole("Trainer"); 

      await _roleManager.CreateAsync(trainerRole); 

      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "bookings.viewrelated")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "bookings.updatestatus")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "contacts.viewrelated")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "locations.viewrelated")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "attendee.view")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "attendee.create")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "attendee.update")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "attendee.delete")); 
     } 

     if (await _roleManager.FindByNameAsync("Booking Management") == null) 
     { 
      //Add Traininer Role 
      var trainerRole = new IdentityRole("Booking Management"); 

      await _roleManager.CreateAsync(trainerRole); 

      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "companies.view")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "companies.create")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "companies.edit")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "companies.delete")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "locations.view")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "locations.create")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "locations.update")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "locations.delete")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "contacts.view")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "contacts.create")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "contacts.update")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "contacts.delete")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "bookings.view")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "bookings.create")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "bookings.update")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "bookings.updatestatus")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "bookings.cancel")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "bookings.delete")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "attendee.view")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "attendee.create")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "attendee.update")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "attendee.delete")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "courses.view")); 
     } 

     if (await _roleManager.FindByNameAsync("Management") == null) 
     { 
      //Add Traininer Role 
      var trainerRole = new IdentityRole("Management"); 

      await _roleManager.CreateAsync(trainerRole); 

      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "reporting.finance")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "reporting.customers")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "users.view")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "users.create")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "users.update")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "users.delete")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "config.view")); 


     } 

     if (await _roleManager.FindByNameAsync("Course Management") == null) 
     { 
      //Add Traininer Role 
      var trainerRole = new IdentityRole("Course Management"); 

      await _roleManager.CreateAsync(trainerRole); 

      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "courses.view")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "courses.create")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "courses.update")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "courses.delete")); 

     } 

     if (await _roleManager.FindByNameAsync("Admin") == null) 
     { 
      //Add Traininer Role 
      var trainerRole = new IdentityRole("Admin"); 

      await _roleManager.CreateAsync(trainerRole); 

      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "config.view")); 
      await _roleManager.AddClaimAsync(trainerRole, new Claim(CustomClaimTypes.Permission, "config.update")); 
     } 

при входе в сервер тождественности моих права доступа список Identity Server User Permissions List

Когда я логин с помощью моего клиента MVC Я не получаю разрешение на пользователе Identity Server Client

В моем клиенте MVC я хочу, чтобы иметь возможность сделать что-то подобное в моей навигации

@if (user.HasClaim(CustomClaimTypes.Permission, "config.view")) 
     { 
     <li> 
      <a href="#"><i class="fa fa-cogs"></i> <span class="nav-label" data-i18n="nav.layouts">Configuration Settings</span></a> 
      <ul class="nav nav-second-level collapse"> 
       <li> 
        <a href="/configuration#!/awardingbodies/"> <span class="nav-label" data-i18n="nav.layouts">Awarding Bodies</span></a> 
       </li> 
      </ul> 
     </li> 
     } 

В идеале я предполагаю, что проверка прав доступа вы не хотите постоянно запросов к базе данных, поэтому я полагаю, лучше, чтобы получить разрешения с токеном, но я потерял, как это сделать?

EDIT 1: Config Клиента в удостоверении Server (Config.cs)

new Client 
      { 
       ClientId = "webclientmvc", 
       ClientName = "CRM MVC Client", 
       AllowedGrantTypes = GrantTypes.Hybrid, 
       AlwaysSendClientClaims = true, 


       RequireConsent = true, 

       ClientSecrets = 
       { 
        new Secret("secret".Sha256()) 
       }, 

       RedirectUris = { "http://localhost:5009/signin-oidc" }, 
       PostLogoutRedirectUris = { "http://localhost:5009" }, 

       AllowedScopes = 
       { 
        StandardScopes.OpenId.Name, 
        StandardScopes.Profile.Name, 
        StandardScopes.OfflineAccess.Name, 
        StandardScopes.Roles.Name, 
        StandardScopes.AllClaims.Name, 
        "api1", 
        "claims" 
       } 
      }, 

Config в клиенте MVC (startup.cs)

public void Configure(IApplicationBuilder app, IHostingEnvironment env,  ILoggerFactory loggerFactory) 
    { 
     JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); 

     loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
     loggerFactory.AddDebug(); 

     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
     } 
     else 
     { 
      app.UseExceptionHandler("/Home/Error"); 
     } 

     app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      AuthenticationScheme = "Cookies", 
      AutomaticChallenge = true, 
      AutomaticAuthenticate = true, 
     }); 

     app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions 
     { 
      AuthenticationScheme = "oidc", 
      SignInScheme = "Cookies", 

      Authority = "http://localhost:5000", 
      RequireHttpsMetadata = false, 

      ClientId = "webclientmvc", 
      ClientSecret = "secret", 

      ResponseType = "code id_token", 
      Scope = { "profile", "api1", "offline_access", "roles" }, 


      GetClaimsFromUserInfoEndpoint = true, 
      SaveTokens = true 


     }); 


     app.UseStaticFiles(); 
     app.UseMvcWithDefaultRoute(); 
    } 
+0

Извините, не ясно, я использую IdentityServer4 – RichardB

+0

Можете ли вы включить код, в котором вы настраиваете клиента на сервере идентификации? – Suhas

+0

Конфигурация клиента Identity Server и клиента MVC была добавлена ​​@Suhas в вопрос, спасибо, что посмотрели. – RichardB

ответ

0

Я получил это работает в настоящее время, но интересно, может ли кто-нибудь прокомментировать, правильно ли это. Я Реализован свой собственный IProfileService из примера я нашел в Интернете, но затем изменил роли часть к этому:

if (_userManager.SupportsUserRole) 
     { 
      var roles = await _userManager.GetRolesAsync(user); 
      claims.AddRange(roles.Select(role => new Claim(JwtClaimTypes.Role, role))); 

      foreach (var item in roles) 
      { 
       var role = await _roleManager.FindByNameAsync(item); 
       if (!(role == null)) 
       { 
        claims.AddRange(await _roleManager.GetClaimsAsync(role)); 
       } 
      } 
     } 

Реализация по умолчанию, кажется, не включает в себя требование, когда они назначены роли, так что мое решение было в цикл через роли и получить заявки и добавить их, это работает, и теперь я могу использовать их на своем веб-сайте MVC.

+0

https://blog.dkbe.ch/2016/09/13/include-user-properties-in-identityserver4-with-asp-net-identity/ – Watson