为Sitecore 9.1实施自定义身份服务器4

时间:2019-05-23 01:40:37

标签: authentication sitecore identityserver4 federated

我要安装一个外部身份服务器4来代替安装过程中的现成的Sitecore 9.1身份服务器。

我已经使用-https://github.com/IdentityServer/IdentityServer4.Quickstart.UI

设置了自己的身份服务器4

我已禁用sitecore实例的现有身份服务器,并配置了sitecore配置以匹配身份服务器。 我还写了一个身份提供者-进程核心,将ID与OpenIdConnectAuthenticationOptions

连接

我遇到错误参数名称:userName 异常:System.ArgumentNullException 消息:值不能为空。 参数名称:userName 资料来源:Microsoft.AspNet.Identity.Core    在Microsoft.AspNet.Identity.UserManager`2.FindByNameAsync(String userName)    在Sitecore.Owin.Authentication.Pipelines.Initialize.HandleLoginLink.d__26.MoveNext()

我检查了是否有一个任务-Sitecore.Owin.Authentication.Pipelines.Initialize中的SignInShadowUserAsync(ExternalLoginInfo loginInfo,IOwinContext上下文)用于处理外部登录链接。

谁能建议我我要去哪里错了? 请在下面找到我使用的配置和代码。

配置:

<?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;
        }
```

0 个答案:

没有答案