Вход в бэк-офис Umbraco 8 с помощью IdentityServer4 - PullRequest
0 голосов
/ 07 марта 2020

Фон

Я довольно новичок в Umbraco, но пытаюсь использовать IdentityServer4 для BackOffice of Umbraco. Для IDP я использовал конфигурацию в памяти (шаблон is4inmem), найденную здесь .

Для Umbraco я использовал UmbracoIdentityExtensions для настройки OpenId Connect .

Я в основном следовал этому учебнику (однако для Umbraco 7).

Проблема

У меня есть кнопка «Войти через OpenId connect», которую я настроил, но когда я пытаюсь войти в систему, используя IDP, Umbraco не входит в систему. Я продолжаю возвращаться на страницу входа. Однако, когда я go захожу на страницу IDP, я захожу в систему и вижу, что мне предоставлен доступ, как показано на рисунке ниже. enter image description here

Всякий раз, когда я вхожу в систему с учетной записью Umbraco, а затем пытаюсь «связать вашу учетную запись OpenId Connect», она ничего не делает, но при выходе из системы появляется сообщение об ошибке в Экран: «Произошла ошибка, не удалось получить информацию о внешнем входе в систему» ​​Я пытался использовать другие параметры конфигурации, но безуспешно.

Код

Конфигурация IDP. cs

public static IEnumerable<IdentityResource> Ids =>
            new IdentityResource[]
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile(),
                new IdentityResources.Email(),
                new IdentityResource(
                    name: "application.profile",
                    displayName: "Application profile",
                    claimTypes: new[] { ClaimTypes.GivenName, ClaimTypes.Surname }
                )
            };

... etc ...

 public static IEnumerable<Client> Clients =>
            new Client[]
            {
                new Client
                {
                    ClientId = "u-client-bo",
                    ClientSecrets = new List<Secret>
                    {
                        new Secret("secret".Sha256()),
                    },
                    ClientName = "Umbraco Client",
                    AllowedGrantTypes = GrantTypes.Hybrid,
                    RequireConsent = false,
                    RedirectUris           = { "https://localhost:44302/Umbraco" },
                    PostLogoutRedirectUris = { "https://localhost:44302/Umbraco" },
                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        IdentityServerConstants.StandardScopes.Email,
                        "application.profile",
                    },
                    AllowAccessTokensViaBrowser = true,
                    AlwaysIncludeUserClaimsInIdToken = false
                }
            };

Для Umbraco я отредактировал UmbracoCustomOwinStartup следующим образом:

public class UmbracoCustomOwinStartup : UmbracoDefaultOwinStartup
{
    protected override void ConfigureUmbracoUserManager(IAppBuilder app)
    {
        app.ConfigureUserManagerForUmbracoBackOffice(
            Services,
            Mapper,
            UmbracoSettings.Content,
            GlobalSettings,

            global::Umbraco.Core.Security.MembershipProviderExtensions.GetUsersMembershipProvider().AsUmbracoMembershipProvider());
    }

    protected override void ConfigureUmbracoAuthentication(IAppBuilder app)
    {
        app
            .UseUmbracoBackOfficeCookieAuthentication(UmbracoContextAccessor, RuntimeState, Services.UserService, GlobalSettings, UmbracoSettings.Security, PipelineStage.Authenticate)
            .UseUmbracoBackOfficeExternalCookieAuthentication(UmbracoContextAccessor, RuntimeState, GlobalSettings, PipelineStage.Authenticate)
            .UseUmbracoPreviewAuthentication(UmbracoContextAccessor, RuntimeState, GlobalSettings, UmbracoSettings.Security, PipelineStage.Authorize);

        var identityOptions = new OpenIdConnectAuthenticationOptions
        {
            ClientId = "u-client-bo",
            SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
            Authority = "https://localhost:44393",
            RedirectUri = "https://localhost:44302/Umbraco",
            ResponseType = "code id_token token",
            Scope = "openid profile application.profile",
            PostLogoutRedirectUri = "https://localhost:44302/Umbraco",

            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                SecurityTokenValidated = ClaimsTransformer.GenerateUserIdentityAsync
            }
        };

        // Configure BackOffice Account Link button and style
        identityOptions.ForUmbracoBackOffice("btn-microsoft", "fa-windows");
        identityOptions.Caption = "OpenId Connect";

        // Configure AutoLinking
        identityOptions.SetExternalSignInAutoLinkOptions(
            new ExternalSignInAutoLinkOptions(autoLinkExternalAccount: true));

        app.UseOpenIdConnectAuthentication(identityOptions);
    }
}

ClaimsTransformer.GenerateUserIdentityAsyn c Метод добавляет дополнительные претензии к Идентичности.

Не хватает дополнительной конфигурации или компонентов?

Заранее спасибо!

1 Ответ

0 голосов
/ 09 марта 2020

Я наконец понял это. Было несколько проблем:

1. Исправьте auth cook ie

Вместо использования DefaultAuthenticationTypes.ExternalCookie в качестве SignInAsAuthenticationType, я сейчас использую Umbraco.Core.Constants.Security.BackOfficeExternalAuthenticationType.

2. Установите AuthenticationType

Установите AuthenticationType в OpenIdConnectAuthenticationOptions. Он должен совпадать с именем Authority, чтобы работала автоматическая ссылка.

Важно : установить его снова после identityOptions.ForUmbracoBackOffice("btn-microsoft", "fa-windows"); явным образом, так как после него ставится префикс 'Umbraco.' после вызов метода.

3. Включите претензию по электронной почте

Я добавил претензию по электронной почте, это также необходимо для работы автоматической ссылки.

Scope = "openid email profile application.profile",

4. Убедитесь, что у вас есть любая форма заявки на имя

Я установил AlwaysIncludeUserClaimsInIdToken на true в IDP, чтобы заявки на идентификаторы автоматически поступали в Umbraco. Мой ClaimsTransformer выглядит сейчас так:

public class ClaimsTransformer
{
    public static async Task GenerateUserIdentityAsync(
        SecurityTokenValidatedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
    {
        // Now this contains ID claims (e.g. GivenName in my case)
        var id = notification.AuthenticationTicket.Identity;

        var identityUser = new ClaimsIdentity(
            id.Claims, // copy the claims I have
            notification.AuthenticationTicket.Identity.AuthenticationType,
            // set the nameType, so Umbraco can use the 'ExternalLogin.Name' for auto-link to work
            ClaimTypes.GivenName, // <-- You have to set a correct nameType claim
            ClaimTypes.Role);

         notification.AuthenticationTicket = new AuthenticationTicket(identityUser,
                notification.AuthenticationTicket.Properties);
    }
}

5. Удалите другое промежуточное ПО Umbraco Auth

В моем случае операторы app.UseUmbracoBackOfficeXXX не были нужны, фактически они нарушили функциональность. Мой UmbracoCustomOwinStartup выглядит следующим образом:

public class UmbracoCustomOwinStartup : UmbracoDefaultOwinStartup
{
    protected override void ConfigureUmbracoAuthentication(IAppBuilder app)
    {
        base.ConfigureUmbracoAuthentication(app);

        var identityOptions = new OpenIdConnectAuthenticationOptions
        {
            ClientId = "u-client-bo",
            SignInAsAuthenticationType = Umbraco.Core.Constants.Security.BackOfficeExternalAuthenticationType,
            AuthenticationType = "https://localhost:44393",
            Authority = "https://localhost:44393",
            RedirectUri = "https://localhost:44302/Umbraco",
            ResponseType = "code id_token token",
            Scope = "openid email profile application.profile",
            PostLogoutRedirectUri = "https://localhost:44302/Umbraco",

            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                SecurityTokenValidated = ClaimsTransformer.GenerateUserIdentityAsync
            }
        };

        // Configure BackOffice Account Link button and style
        identityOptions.ForUmbracoBackOffice("btn-microsoft", "fa-windows");
        identityOptions.Caption = "OpenId Connect";

        identityOptions.AuthenticationType = "https://localhost:44393";

        // Configure AutoLinking
        identityOptions.SetExternalSignInAutoLinkOptions(
            new ExternalSignInAutoLinkOptions(autoLinkExternalAccount: true));

        app.UseOpenIdConnectAuthentication(identityOptions);
    }

}

Совет: не забудьте использовать правильный запуск OWIN в вашем web.config.

Я надеюсь, что некоторые из вас нашли это полезным Я не смог найти много документации по Umbraco 8 в сочетании с IdentityServer4.

...