在另一个域

时间:2017-09-13 18:28:52

标签: security authentication oauth identityserver3 identitymanager

在通过IdentityServer进行身份验证后,IdentityManager会发出这样的内部令牌。 (请运行the example并检查请求/ api或api / Users后发送的持票人令牌

authorization:Bearer UQgpIqqyn_lgUukES3PqHFEuf0_2sz26Jsh848K_4DYdiYeQLkSazg43MT2BdWSC-EY--iUYAPKk4rD9-8sq0_nbf2Z7XDzPlcDL0LdAP8oNyKUDCOLeap9zCEaB4ve1VE1Q_e5JGYsx_jTvs-yYlUI5fMn-6OBxunlNcTwPq-xv6hOXZhh-PUGIE9Ndhkptd0zt5r1A3UAvvTk72yI6yD40yRnl1KhNEQw33UNVMIeV4vWqwiXHtyoxi87e3r4_x3IyzZeEqxtwPIPH1l6o1s7HfZozspaTbaq9gPLvuaXa0dQjf5lA2CIGs5z8Fa3W

我实际上需要IdentityManager在登录过程中保存我自己的IdentityServer发出的JWT,并使用该令牌调用api而不是使用上述类型的令牌。为什么?因为我想从IdentityManager本身调用一个外部API,它期望我自己的IdentityServer服务器发出一个令牌。

使用HostSecurityConfiguration或LocalSecurityConfiguration对我不起作用,因为他们在内部使用OAuthAuthorizationServerProvider,并且该提供程序发出一个令牌(上面的那个),它对最终IdentityManager内部将要调用的API无效。令牌已保存必须由我自己的IdentityServer发出,因为外部API需要来自它的令牌。

我尝试使用ExternalBearerTokenConfiguration但没有成功。每次我尝试用这个课做某事我都会被重定向到 https://localhost:44337/idm/connect/authorize?state=8030030589322682&nonce=7778993666881238&client_id=idmgr&response_type=id_token%20token 并且此URL显然不存在,因为权限以https://localhost:44337/ids开头,而ExternalBearerTokenConfiguration假定我的提供者位于同一域下。

这是ExternalBearerTokenConfiguration的配置

idm.UseIdentityManager(new IdentityManagerOptions
            {
                Factory = factory,
                SecurityConfiguration = new ExternalBearerTokenConfiguration()
                {
                    RequireSsl = false,
                    SigningCert = Cert.Load(),
                    Issuer = "https://localhost:44337/ids",
                    Scope = "idmgr",
                    Audience = $"https://localhost:44337/ids/resources",
                    BearerAuthenticationType = "Cookies"
                }
            });

走向另一个方向,我发现在IdentityManager.Assets.EmbeddedHtmlResult上修改方法GetResponseMessage()我可以去我的IdentityServer,我要求认证,这是非常好的。正如你所看到的,我可以获取我的id_token和访问令牌。对这种方法的好想法是内部保存的令牌是我从IdentityServer获得的令牌。

{
    "client_id": "idmgr_client",
    "scope": [
    "openid",
    "idmgr",
    "WebUserAccountsApi"
    ],
    "sub": "951a965f-1f84-4360-90e4-3f6deac7b9bc",
    "amr": [
    "password"
    ],
    "auth_time": 1505323819,
    "idp": "idsrv",
    "name": "Admin",
    "role": "IdentityManagerAdministrator",
    "iss": "https://localhost:44336/ids",
    "aud": "https://localhost:44336/ids/resources",
    "exp": 1505327419,
    "nbf": 1505323819
}

所以现在我几乎得到了所需的一切,当IdentityServer将我发送回我的/ idm端点(IdentityManager的端点)时,UseIdentityServerBearerTokenAuthentication验证我的令牌,因此我获得了授权,我确信它因为我可以在下面的代码中查看此行中的所有内容=> context.Authentication.User.Identity.IsAuthenticated。问题是,即使UseIdentityServerBearerTokenAuthentication已经执行,UseIdentityManager也不会获得我的授权。

当我删除I​​dentityManager项目中的安全性并在api / Users中放置一个断点时,我可以看到Principal有一些值但是所有值都是空的。声明是空的,身份本身有一个对象但未经过身份验证。可能我在这段代码中遗漏了一些东西,它是我的UseIdentityServerBearerTokenAuthentication身份验证和UseIdentityManager之间的粘合剂。

app.Map("/idm", idm =>
{
    var factory = new IdentityManagerServiceFactory();

    var rand = new System.Random();
    var users = Users.Get(rand.Next(5000, 20000));
    var roles = Roles.Get(rand.Next(15));

    factory.Register(new Registration<ICollection<InMemoryUser>>(users));
    factory.Register(new Registration<ICollection<InMemoryRole>>(roles));
    factory.IdentityManagerService = new Registration<IIdentityManagerService, InMemoryIdentityManagerService>();

    idm.Use(async (context, next) =>
    {
        await next.Invoke();
    });
    JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

    idm.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
    {
        Authority = Constants.authority,
        RequiredScopes = new[] { "idmgr" }
    });

    idm.Use(async (context, next) =>
    {
        if (context.Authentication.User != null &&
                context.Authentication.User.Identity != null &&
                context.Authentication.User.Identity.IsAuthenticated)
        {
            /*var xxx = "";
        }
        await next.Invoke();
    });


    idm.UseIdentityManager(new IdentityManagerOptions
    {
        Factory = factory
    });

    idm.Use(async (context, next) =>
    {
        await next.Invoke();
    });
});

如果您知道我遗漏了什么,请发表评论。所有的想法都受到欢迎。 如果您知道如何使用自己的IdentityServer在IdentityManager中进行身份验证,请告诉我该怎么做。

提前致谢。 丹尼尔

2 个答案:

答案 0 :(得分:0)

IdentityManager存储库使用IdentityServer3作为IdentityManager的Idp an example

可以找到一些相关的讨论in this thread ......

编辑:

我没有像你描述的那样研究IdentityManager在内部使用令牌做什么。但是,对于外部API调用,您是否也无法请求访问令牌(而不仅仅是id_token),然后保存该访问令牌并使用它来调用外部API?这将是Identity Server发出的令牌,默认情况下它将是JWT。

以下是示例中的代码将如何更改;请参阅标记为“--EDIT-- ...”的两条评论下的代码。

基本上,我只是请求和访问令牌,然后保存它....

app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions
{
    AuthenticationType = "oidc",
    Authority = "https://localhost:44337/ids",
    ClientId = "idmgr_client",
    RedirectUri = "https://localhost:44337",

    // ---EDIT--- request id_token AND access_token
    ResponseType = "id_token token",

    UseTokenLifetime = false,
    Scope = "openid idmgr",
    SignInAsAuthenticationType = "Cookies",
    Notifications = new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationNotifications
    {
        SecurityTokenValidated = n =>
        {
            n.AuthenticationTicket.Identity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));

            // --EDIT-- save access_token
            n.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));

            return Task.FromResult(0);
        },
        RedirectToIdentityProvider = async n =>
        {
            if (n.ProtocolMessage.RequestType == Microsoft.IdentityModel.Protocols.OpenIdConnectRequestType.LogoutRequest)
            {
                var result = await n.OwinContext.Authentication.AuthenticateAsync("Cookies");
                if (result != null)
                {
                    var id_token = result.Identity.Claims.GetValue("id_token");
                    if (id_token != null)
                    {
                        n.ProtocolMessage.IdTokenHint = id_token;
                        n.ProtocolMessage.PostLogoutRedirectUri = "https://localhost:44337/idm";
                    }
                }
            }
        }
    }
});

答案 1 :(得分:0)

我找到了解决方案。

我创建了一个名为OAuthSettings的类,另一个名为EmptySecurityConfiguration。我正在使用它们:

idm.UseIdentityManager(new IdentityManagerOptions
            {
                Factory = factory,
                SecurityConfiguration = new EmptySecurityConfiguration
                {
                    OAuthSettings = new OAuthSettings()
                    {
                        authorization_endpoint = authority + "/connect/authorize",
                        client_id = "idmgr_client",
                        authority = authority,
                        response_type = "id_token token",
                        redirect_uri = idmUrl + "/#/callback/",
                        //scope = "openid",
                        scope = "openid idmgr MyApi",
                        //response_mode = ""
                        acr_values = "tenant:anything",
                        load_user_profile = true
                    }
                }
            });

我必须修改SecurityConfiguration类才能添加我的OAuthSettings属性。

然后我在EmbeddedHtmlResult

中使用它
OAuthSettings OAuthSettings = null;
        if (this.securityConfiguration.OAuthSettings == null)
        {
            OAuthSettings = new OAuthSettings
            {
                authorization_endpoint = this.authorization_endpoint,
                client_id = Constants.IdMgrClientId
            };
        }
        else
        {
            OAuthSettings = this.securityConfiguration.OAuthSettings;
        }

        var html = AssetManager.LoadResourceString(this.file,
            new {
                pathBase = this.path,
                model = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    PathBase = this.path,
                    ShowLoginButton = this.securityConfiguration.ShowLoginButton,
                    oauthSettings = OAuthSettings
                })
            });

之后你必须运行代码并且那就是它。您已获得IdentityServer颁发的令牌并将其保存以便在javascript位中使用。

现在,Bearer Token看起来像这样:

authorization:Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSIsImtpZCI6ImEzck1VZ01Gdjl0UGNsTGE2eUYzekFrZnF1RSJ9.eyJjbGllbnRfaWQiOiJpZG1ncl9jbGllbnQiLCJzY29wZSI6WyJvcGVuaWQiLCJpZG1nciIsIk15QXBpIl0sInN1YiI6Ijk1MWE5NjVmLTFmODQtNDM2MC05MGU0LTNmNmRlYWM3YjliYyIsImFtciI6WyJwYXNzd29yZCJdLCJhdXRoX3RpbWUiOjE1MDU1NzYzNTAsImlkcCI6Imlkc3J2IiwibmFtZSI6IkFkbWluIiwicm9sZSI6IklkZW50aXR5TWFuYWdlckFkbWluaXN0cmF0b3IiLCJpc3MiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzOC9pZHMiLCJhdWQiOiJodHRwczovL2xvY2FsaG9zdDo0NDMzOC9pZHMvcmVzb3VyY2VzIiwiZXhwIjoxNTA1NTgwMzU4LCJuYmYiOjE1MDU1NzY3NTh9.iVsEuswGDdMGo-x-NdPxMEln6or9e7p8G-8iSK746_Wapcwi_-N7EcY3G8GKj0YvExO4i605kfNjsTDAd14zQvT6UyU8_gcGO84DhQRM_MWpirfhlPWu6flXT4dRzYberjgHhDEOzROsrHofVAAZD_51BEE1FgAQrqCCWar2POSi9AsLFJ_AxFRnMlbZbZy8adJiMGOUFhtBXzhJVYzuolAMJ08NBTzmaK5vLsEn9Ok-09ZGX3MOpq2aBfES1hRJKEP-LDhMNo4dQn0mQ9Y-gGvkpXMmZQ6tC8yUs2PokJ5eGsFqevK6zpvJDiKPPjoN01QJtEqZ2UU_oGzMEKwyUA

我使用code

创建了一个github存储库