IdentityServer v4的ASP.NET Core客户端中的通知

时间:2016-10-18 16:30:02

标签: asp.net-core asp.net-core-mvc identityserver3 asp.net-core-1.0 identityserver4

在IdentityServer 3中,我在通知上使用SecurityTokenValidated事件来建立我自己的身份名称和声明。例如,我使用资源所有者工作流将access_token存储到以后访问n API,如下所示:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
AuthenticationType = "oidc",

// ...

Notifications = new OpenIdConnectAuthenticationNotifications
{
    SecurityTokenValidated = async n =>
    {
        var nid = new ClaimsIdentity(
          n.AuthenticationTicket.Identity.AuthenticationType,
          "name",
          ClaimTypes.Role);
        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
        nid.AddClaim(new Claim("access_token", n.ProtocolMessage.AccessToken));
        nid.AddClaim(new Claim("expires_at", DateTimeOffset.Now.AddSeconds(int.Parse(n.ProtocolMessage.ExpiresIn)).ToString()));
    }
}
}

在IdentityServer 4 for ASP.NET Core中不是Notifications属性。 我可以看到有很多声明自动生成但我没有得到access_token,也没有自动设置身份的用户名

我在ASP.NET Core中的客户端的当前配置如下所示

   app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            AuthenticationScheme = "oidc",
            SignInScheme = "Cookies",
            Authority = identityServerUri,
            RequireHttpsMetadata = false,
            ClientId = clientId,
            ResponseType = "id_token token",
            Scope =
            {
                "openid profile email warehouseapi"
            },
            GetClaimsFromUserInfoEndpoint = true,
            SaveTokens = true,
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
        });

IdentityServer 4的目的是什么?

2 个答案:

答案 0 :(得分:2)

这实际上与IdentityServer4无关。 OWIN和AspNetCore变体中的身份验证中间件之间的区别更大。

这些通知现在更正确地命名为Events

您可以使用以下方法执行类似操作:

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    AuthenticationScheme = "oidc",
    SignInScheme = "Cookies",

    Authority = "https://demo.identityserver.io",
    PostLogoutRedirectUri = "http://localhost:3308/",
    ClientId = "hybrid",
    ClientSecret = "secret",
    ResponseType = "code id_token",
    GetClaimsFromUserInfoEndpoint = true,
    SaveTokens = true,

    Events = new OpenIdConnectEvents
    {
        OnTokenValidated = async n =>
        {

        }
    }
});

您可以找到所有不错的活动here

答案 1 :(得分:2)

您可以使用TickedReceived事件转换声明:

        var oidcOptions = new OpenIdConnectOptions
        {
            ...
            Events = new OpenIdConnectEvents()
            {
                // get access token
                OnTicketReceived = ctx =>
                {
                    // transform claims
                    var access_token = ctx.Ticket.Properties.GetTokenValue("access_token");
                    return Task.FromResult(0);
                }
            }
        };

此外,您不需要将令牌保存为声明,因为当您将SaveTokens设置为true时,令牌会自动保存在身份验证属性中。要获取令牌,您可以使用HttpContext.Authentication.GetTokenAsync("<token name>")