Travis Collins
Travis Collins

Reputation: 4020

How to populate local info into User.Identity when using app.UseIdentityServerBearerTokenAuthentication()

How can I populate the data from my local AspNetUsers into the User.Identity object, so that it can be utilized in ApiControllers?

I am working on an ASP.NET client application that is using an IdentityServer3 application as it's Authentication provider. I am sending a bearer token in the Authorization header, which seems to be working well. In my client application, I am using the following middleware:

    app.UseIdentityServerBearerTokenAuthentication(
        new IdentityServerBearerTokenAuthenticationOptions
        {
            Authority = settingsService.SsoProviderUrl + "/core/"
        }
    );

Currently User.Identity contains the information from the OpenId Connect provider. Great! But I would like to also include information regarding the local user. I have data in AspNetUsers and AspNetUserLogins to represent the user locally (AspNetUserLogins.ProviderKey is equal to the user's subscriber id on OpenId Connect).

How can I populate the data from my local AspNetUsers into the User.Identity object, so that it can be utilized in ApiControllers? I can get ahold of the data fine, it's just a matter of getting that data into User.Identity that has me stumped.

Upvotes: 1

Views: 634

Answers (1)

Travis Collins
Travis Collins

Reputation: 4020

The solution I landed on was to create my own middleware which plugs in to the pipeline after UseIdentityServerBearerTokenAuthentiation(). The new middleware simply retrieves the data that I want added, and adds the claims to current identity. Example code:

app.Use(async (context, next) =>
{
    if (context.Authentication.User.Identity.IsAuthenticated)
    {
        var identity = context.Authentication.User.Identities.First();
        // Access claims
        var idClaim = identity.FindFirst(ClaimTypes.NameIdentifier);
        string subscriberId = idClaim.Value;

        // your custom code to obtain user information from your database
        var dbUser = await userService.FindAsync(new UserLoginInfo("MyProviderName", subscriberId));

        // put your custom user information into the claims for the current identity.
        identity.AddClaim(new Claim("name", dbUser.UserName));
        identity.AddClaim(new Claim("favorite-color", dbUser.FavoriteColor));
        // and so on

    }

    await next.Invoke();
});

Upvotes: 1

Related Questions