Реализация Custom Identity Server 4 для Sitecore 9.1 - PullRequest
0 голосов
/ 23 мая 2019

Я устанавливаю внешний идентификационный сервер 4 вместо готового идентификационного сервера sitecore 9.1, который идет через установку.

Я настроил свой собственный идентификационный сервер 4, используя - https://github.com/IdentityServer/IdentityServer4.Quickstart.UI

Я отключил существующий сервер идентификации экземпляра sitecore и настроил конфигурацию sitecore для соответствия серверу идентификации.Я также написал провайдеры идентификации - ядро ​​процесса для соединения идентификатора с OpenIdConnectAuthenticationOptions

Я сталкиваюсь с ошибкой Имя параметра: userName Exception: System.ArgumentNullException Сообщение: значение не может быть нулевым.Имя параметра: userName Источник: Microsoft.AspNet.Identity.Core в Microsoft.AspNet.Identity.UserManager`2.FindByNameAsync (String userName) в Sitecore.Owin.Authentication.Pipelines.Initialize.HandleLoginLink.d__26.MoveNext (

Я проверил, что существует задача - SignInShadowUserAsync (ExternalLoginInfo loginInfo, IOwinContext context) в Sitecore.Owin.Authentication.Pipelines.Initialize для обработки внешней ссылки входа.

Кто-нибудь может подсказать мне, где я иду не так?Пожалуйста, найдите ниже конфигурацию и код, который я использовал.

Конфиг:

<?xml version="1.0" encoding="utf-8"?>

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:set="http://www.sitecore.net/xmlconfig/set/">
  <sitecore role:require="Standalone or ContentDelivery or ContentManagement">
    <sc.variable name="identityServerAuthority" value="https://localhost:44311/" />

    <settings>
      <!-- The URI of the IdentityServer provider. -->
      <setting name="FederatedAuthentication.IdentityServer.Authority" value="$(identityServerAuthority)" />
      <!-- The client identifier on the IdentityServer. -->
      <setting name="FederatedAuthentication.IdentityServer.ClientId" value="Sitecore" />
      <!-- The client identifier for the Resource Owner Password flow on the IdentityServer. -->
      <setting name="FederatedAuthentication.IdentityServer.ResourceOwnerClientId" value="SitecorePassword" />
      <setting name="PostLogoutRedirectURI" value="https://sc914.local/sitecore/login" />
      <setting name="AuthenticationRedirectUri" value="https://sc914.local" />
    </settings>

    <services>
      <configurator type="Sitecore.Owin.Authentication.IdentityServer.ServicesConfigurator, Sitecore.Owin.Authentication.IdentityServer" />
    </services>

    <pipelines>
      <owin.identityProviders>
      <!--  <processor type="Sitecore.Owin.Authentication.IdentityServer.Pipelines.IdentityProviders.ConfigureIdentityServer, Sitecore.Owin.Authentication.IdentityServer" resolve="true" id="SitecoreIdentityServer">
                  <scopes hint="list">
            <scope name="openid">openid</scope>
            <scope name="sitecore.profile">sitecore.profile</scope>
          </scopes>
        </processor>
-->     <processor type="Foundation.Authentication.IdentityProviderProcessor, Foundation.Authentication" id="SitecoreIdentityServer" resolve="true" >          
        </processor>
      </owin.identityProviders>
      <owin.initialize>
        <processor type="Sitecore.Owin.Authentication.IdentityServer.Pipelines.Initialize.InterceptLegacyShellLoginPage, Sitecore.Owin.Authentication.IdentityServer" patch:before="processor[@method='Authenticate']" resolve="true">
          <legacyShellLoginPage>/sitecore/login</legacyShellLoginPage>
        </processor>
        <processor type="Sitecore.Owin.Authentication.IdentityServer.Pipelines.Initialize.JwtBearerAuthentication, Sitecore.Owin.Authentication.IdentityServer" patch:before="processor[@method='Authenticate']" resolve="true">
          <identityProviderName>SitecoreIdentityServer</identityProviderName>
          <audiences hint="raw:AddAudience">
            <audience value="$(identityServerAuthority)/resources" />
          </audiences>
          <issuers hint="list">
            <issuer>$(identityServerAuthority)</issuer>
          </issuers>
        </processor>
      </owin.initialize>
    </pipelines>

    <federatedAuthentication>
      <identityProvidersPerSites>
        <mapEntry name="sites with the core and unspecified database">
          <identityProviders hint="list:AddIdentityProvider">
            <identityProvider ref="federatedAuthentication/identityProviders/identityProvider[@id='SitecoreIdentityServer']" id="SitecoreIdentityServer" />
          </identityProviders>
                  <externalUserBuilder type="Foundation.Authentication.CreateUniqueUser, Foundation.Authentication">
                        <param desc="isPersistentUser">true</param>
                    </externalUserBuilder>
        </mapEntry>
        <!-- An example that maps a sub-provider of the Identity Server to the sites that are not mapped to the SitecoreIdentityServer. -->
        <!--
        <mapEntry name="all sites">
          <identityProviders hint="list:AddIdentityProvider">
            <identityProvider ref="federatedAuthentication/identityProviders/identityProvider[@id='SitecoreIdentityServer/IdS4-AzureAd']" />
          </identityProviders>
        </mapEntry>
        -->
        <mapEntry name="all sites" type="Sitecore.Owin.Authentication.Collections.IdentityProvidersPerSitesMapEntry, Sitecore.Owin.Authentication">
                    <sites hint="list">                     
                        <site>website</site>                        
                    </sites>
          </mapEntry>
      </identityProvidersPerSites>

      <identityProviders>
        <identityProvider id="SitecoreIdentityServer" type="Sitecore.Owin.Authentication.IdentityServer.IdentityServerProvider, Sitecore.Owin.Authentication.IdentityServer" resolve="true">
          <caption>Go to login</caption>
          <domain>sitecore</domain>
          <enabled>true</enabled>
          <triggerExternalSignOut>true</triggerExternalSignOut>
          <transformations hint="list:AddTransformation">
           <transformation name="Name Identifier Claim" type="Sitecore.Owin.Authentication.Services.DefaultTransformation, Sitecore.Owin.Authentication">
    <sources hint="raw:AddSource">
      <claim name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" />
    </sources>
    <targets hint="raw:AddTarget">
      <claim name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" />
    </targets>
    <keepSource>false</keepSource>
  </transformation>
            <transformation name="apply additional claims" type="Sitecore.Owin.Authentication.IdentityServer.Transformations.ApplyAdditionalClaims, Sitecore.Owin.Authentication.IdentityServer" resolve="true" />
            <transformation name="name to long name" type="Sitecore.Owin.Authentication.Services.DefaultTransformation, Sitecore.Owin.Authentication">
              <sources hint="raw:AddSource">
                <claim name="name" />
              </sources>
              <targets hint="raw:AddTarget">
                <claim name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" />
              </targets>
              <keepSource>true</keepSource>
            </transformation>
            <transformation name="role to long role" type="Sitecore.Owin.Authentication.Services.DefaultTransformation, Sitecore.Owin.Authentication">
              <sources hint="raw:AddSource">
                <claim name="role" />
              </sources>
              <targets hint="raw:AddTarget">
                <claim name="http://schemas.microsoft.com/ws/2008/06/identity/claims/role" />
              </targets>
              <keepSource>false</keepSource>
            </transformation>
            <transformation name="set ShadowUser" type="Sitecore.Owin.Authentication.Services.DefaultTransformation, Sitecore.Owin.Authentication">
              <sources hint="raw:AddSource">
                <claim name="http://schemas.microsoft.com/identity/claims/identityprovider" value="local" />
              </sources>
              <targets hint="raw:AddTarget">
                <claim name="http://www.sitecore.net/identity/claims/shadowuser" value="true" />
              </targets>
              <keepSource>true</keepSource>
            </transformation>
            <!-- owin.cookieAuthentication.signIn pipeline uses http://www.sitecore.net/identity/claims/cookieExp claim to override authentication cookie expiration.
                 'exp' claim value can be configured on Sitecore Identity server on the client configuration by IdentityTokenLifetimeInSeconds setting.
                 Note: Claim value is Unix time expressed as the number of seconds that have elapsed since 1970-01-01T00:00:00Z -->
            <transformation name="use exp claim for authentication cookie expiration" type="Sitecore.Owin.Authentication.Services.DefaultTransformation, Sitecore.Owin.Authentication">
              <sources hint="raw:AddSource">
                <claim name="exp" />
              </sources>
              <targets hint="raw:AddTarget">
                <claim name="http://www.sitecore.net/identity/claims/cookieExp" />
              </targets>
              <keepSource>true</keepSource>
            </transformation>
            <transformation name="remove local role claims" type="Sitecore.Owin.Authentication.IdentityServer.Transformations.RemoveLocalRoles, Sitecore.Owin.Authentication.IdentityServer" />
            <transformation name="adjust NameIdentifier claim" type="Sitecore.Owin.Authentication.IdentityServer.Transformations.AdjustNameIdentifierClaim, Sitecore.Owin.Authentication.IdentityServer" resolve="true" />
          </transformations>
        </identityProvider>
        <!-- An example of how to add an identity provider as a sub-provider of the Identity Server.
             The 'name' property must be in the following format: SitecoreIdentityServer/[AuthenticationScheme], where the 'AuthenticationScheme' equals the
             authentication scheme of an external identity provider that is configured on the Identity Server.

             Notes:
               1. The 'TriggerExternalSignOut' and 'Transformations' properties are inherited from the the Identity Server provider node and can not be overridden.
               2. To use a sub-provider, the 'Enabled' property of the Identity Server provider must be set to 'Enabled'. -->
        <!--
        <identityProvider id="SitecoreIdentityServer/IdS4-AzureAd" type="Sitecore.Owin.Authentication.Configuration.DefaultIdentityProvider, Sitecore.Owin.Authentication">
          <param desc="name">$(id)</param>
          <param desc="domainManager" type="Sitecore.Abstractions.BaseDomainManager" resolve="true" />
          <caption>Log in with Sitecore Identity: Azure AD</caption>
          <icon>/sitecore/shell/themes/standard/Images/24x24/msazure.png</icon>
          <domain>sitecore</domain>
        </identityProvider>
        -->
       </identityProviders>
               <sharedTransformations hint="list:AddSharedClaimsTransformation">
            <!--Adds idp claim to identity. Every provider should reference to it-->
           <nameClaimTransformation name="nameClaimTransformation" type="Sitecore.Owin.Authentication.Services.DefaultTransformation, Sitecore.Owin.Authentication">
            <sources hint="raw:AddSource">
                    <claim name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier" />
                </sources>
                 <targets hint="raw:AddTarget">
                    <claim name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" />
                </targets>
           </nameClaimTransformation>
        </sharedTransformations>

      <propertyInitializer>
         <maps>
            <map name="set IsAdministrator" type="Sitecore.Owin.Authentication.Services.DefaultClaimToPropertyMapper, Sitecore.Owin.Authentication">
                <data hint="raw:AddData">
                    <source name="http://www.sitecore.net/identity/claims/isAdmin" value="true" />
                    <target name="IsAdministrator" value="true" />
                </data>
            </map>

                    <map name="name" type="Sitecore.Owin.Authentication.Services.DefaultClaimToPropertyMapper, Sitecore.Owin.Authentication">
                        <data hint="raw:AddData">                   
                            <source name="UserFullName" />                  
                            <target name="FullName" />
                        </data>
                    </map>
                    <map name="name" type="Sitecore.Owin.Authentication.Services.DefaultClaimToPropertyMapper, Sitecore.Owin.Authentication">
                        <data hint="raw:AddData">                   
                            <source name="Username" />                  
                            <target name="userName" value="admin"/>
                        </data>
                    </map>
         </maps>
       </propertyInitializer>

    </federatedAuthentication>

    <sites>
      <site name="shell" set:loginPage="$(loginPath)shell/SitecoreIdentityServer" />
      <site name="admin" set:loginPage="$(loginPath)admin/SitecoreIdentityServer" />
      <site name="website" set:loginPage="$(loginPath)website/SitecoreIdentityServer" />
    </sites>
  </sitecore>
</configuration>
`````

Code:
Process Core :
```
 args.App.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                Caption = identityProvider.Caption,
                Scope = "openid",
                RequireHttpsMetadata = false,
                AuthenticationType = authenticationType,
                AuthenticationMode = AuthenticationMode.Active,
                ResponseType = "code id_token token",
                SignInAsAuthenticationType = "Cookies",
                ClientId = clientId,
                ClientSecret = "secret",
                Authority = authority,
                RedirectUri = redirectUri,
                TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = authority
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    //SecurityTokenValidated allows you to write code after a token has passed validation and you have a Claims Identity

                    //SecurityTokenValidated = n =>
                    //{
                    //    string token = n.ProtocolMessage.AccessToken;
                    //    n.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", token));
                    //    return Task.FromResult(0);
                    //}

                     SecurityTokenValidated = (context) => SecurityTokenValidation(context, identityProvider)

                }
            });
```
```
   private Task SecurityTokenValidation(SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context, IdentityProvider provider)
        {
            ClaimsIdentity identity = context.AuthenticationTicket.Identity;

            foreach (var claimTransformationService in provider.Transformations)
            {
                claimTransformationService.Transform(identity, new TransformationContext(_configuration, provider));
            }

            context.AuthenticationTicket = new AuthenticationTicket(identity, context.AuthenticationTicket.Properties);

            return Task.CompletedTask;
        }
```

...