简体   繁体   English

使用 IdentityServer4 登录 Umbraco 8 后台

[英]Umbraco 8 backoffice login with IdentityServer4

Background背景

I'm quite new to Umbraco but have been trying to use IdentityServer4 for the BackOffice of Umbraco.我对 Umbraco 很陌生,但一直在尝试将IdentityServer4用于 Umbraco 的后台。 For the IDP, I've used the in-memory configuration (is4inmem template) found here .对于 IDP,我使用了在此处找到的内存配置(is4inmem 模板)。

For Umbraco I've used the UmbracoIdentityExtensions to configure OpenId Connect.对于 Umbraco,我使用UmbracoIdentityExtensions来配置 OpenId Connect。

I've been mainly following this tutorial (this is however, for Umbraco 7).我一直主要关注教程(然而,这是 Umbraco 7)。

The problem问题

I do have the 'Sign in with OpenId connect' button which I configured, but when I try to log in using the IDP, Umbraco does not log me in. I keep getting returned to the login page.我确实有我配置的“使用 OpenId 连接登录”按钮,但是当我尝试使用 IDP 登录时,Umbraco 没有让我登录。我一直返回到登录页面。 Whenever I go to the IDP page, however, I am logged in and can see I've given access as seen in the picture below.但是,每当我转到 IDP 页面时,我都已登录并可以看到我已授予访问权限,如下图所示。 在此处输入图片说明

Whenever I log in with an Umbraco account, and then try to 'Link your OpenId Connect account', it does nothing, but upon logging out an error message appears in the screen: 'An error occurred, could not get external login info' I've tried to use different configuration settings, but without success.每当我使用 Umbraco 帐户登录,然后尝试“链接您的 OpenId Connect 帐户”时,它什么也不做,但是在注销时,屏幕上会出现一条错误消息:“发生错误,无法获取外部登录信息”我' 尝试使用不同的配置设置,但没有成功。

Code代码

IDP Config.cs IDP 配置文件

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

For Umbraco, I have edited the UmbracoCustomOwinStartup to the following:对于 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);
    }
}

The ClaimsTransformer.GenerateUserIdentityAsync method adds additional claims to the Identity. ClaimsTransformer.GenerateUserIdentityAsync方法向 Identity 添加其他声明。

Am I missing additional configuration or components?我是否缺少其他配置或组件?

Thanks in advance!提前致谢!

I've finally figured it out.我终于想通了。 There were several issues:有几个问题:

1. Correct the auth cookie 1.更正auth cookie

Instead of using DefaultAuthenticationTypes.ExternalCookie as SignInAsAuthenticationType , I am now using Umbraco.Core.Constants.Security.BackOfficeExternalAuthenticationType .而不是使用DefaultAuthenticationTypes.ExternalCookie作为SignInAsAuthenticationType ,我现在使用Umbraco.Core.Constants.Security.BackOfficeExternalAuthenticationType

2. Set the AuthenticationType 2. 设置认证类型

Set the AuthenticationType in the OpenIdConnectAuthenticationOptions .OpenIdConnectAuthenticationOptions设置AuthenticationType It must match the name of the Authority in order for auto-link to work.它必须与Authority的名称相匹配,以便自动链接工作。

Important : Set it again after identityOptions.ForUmbracoBackOffice("btn-microsoft", "fa-windows");重要提示:在identityOptions.ForUmbracoBackOffice("btn-microsoft", "fa-windows");之后再次设置它identityOptions.ForUmbracoBackOffice("btn-microsoft", "fa-windows"); explicitly since it prefixes it with 'Umbraco.'明确地,因为它以'Umbraco.'作为前缀'Umbraco.' after the method call.在方法调用之后。

3. Include the email claim 3. 包括电子邮件声明

I've added the email claim, this is also required for auto-link to work.我已经添加了电子邮件声明,这也是自动链接工作所必需的。

Scope = "openid email profile application.profile",

4. Ensure that you have any form of name claim 4. 确保您有任何形式的名称声明

I've set AlwaysIncludeUserClaimsInIdToken to true in the IDP, so the id claims get automatically in Umbraco.我已在 IDP 中将AlwaysIncludeUserClaimsInIdToken设置为true ,因此 id 声明会在 Umbraco 中自动获取。 My ClaimsTransformer looks like this now:我的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. Remove other Umbraco Auth middleware 5. 移除其他 Umbraco Auth 中间件

The app.UseUmbracoBackOfficeXXX statements were not needed in my case, in fact, they broke the functionality.在我的例子中不需要app.UseUmbracoBackOfficeXXX语句,事实上,它们破坏了功能。 My UmbracoCustomOwinStartup looks like this now:我的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);
    }

}

tip: Don't forget to use the correct OWIN Startup in your web.config .提示:不要忘记在web.config使用正确的 OWIN 启动。

I hope some of you found this helpful, I couldn't find alot of documentation about Umbraco 8 in combination with IdentityServer4.我希望你们中的一些人发现这有帮助,我找不到很多关于 Umbraco 8 与 IdentityServer4 结合的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM