Home How to get user claims after login with IdentityServer4
Reply: 0

How to get user claims after login with IdentityServer4

martial
1#
martial Published in 2017-12-07 14:41:29Z

I use IdentityServer4 with Asp.net Identity and EF. My client side is an Asp.net MVC (not core). I used this code as my IdentityServer4:

https://github.com/IdentityServer/IdentityServer4.Samples/tree/release/Quickstarts/Combined_AspNetIdentity_and_EntityFrameworkStorage

In table [IdentityClaims] I saw claims like given_name, middle_name, nickname, website etc., but on the client side, when I debug and check by using

var cp = (ClaimsPrincipal)User;

I only see claims like nbf, exp, iss, aud, etc., there is no given_name, middle_name etc. I make sure there are corresponding records in tables [IdentityResources], [IdentityClaims], [ClientScopes], and [AspNetUserClaims] (I assume this is where user put his claims' values). By the way, what is [ClientClaims] for?

The code on my client:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,

        });

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            ClientId = "mvc",
            Authority = "http://localhost:5000",
            RedirectUri = "https://localhost:44388",
            PostLogoutRedirectUri = "https://localhost:44388", 
            ResponseType = "code id_token", 
            Scope = "openid profile api1", 
            ClientSecret = "secret", 
            UseTokenLifetime = false,
            SignInAsAuthenticationType = "Cookies",
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                SecurityTokenValidated = async n =>
                {
                    var id = n.AuthenticationTicket.Identity;

                    id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                    n.AuthenticationTicket = new AuthenticationTicket(
                           id,
                           n.AuthenticationTicket.Properties);
                },
                RedirectToIdentityProvider = n =>
                {
                    if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                    {
                        var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token").Value;
                        n.ProtocolMessage.IdTokenHint = idTokenHint;
                    }
                    return Task.FromResult(0);
                }
            }
        });
    }

The code on IdentityServer4 Startup.cs:

   public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // Add application services.
        services.AddTransient<IEmailSender, EmailSender>();

        services.AddMvc();

        string connectionString = Configuration.GetConnectionString("DefaultConnection");
        var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

        // configure identity server with in-memory stores, keys, clients and scopes
        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddAspNetIdentity<ApplicationUser>()
            // this adds the config data from DB (clients, resources)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                    builder.UseSqlServer(connectionString,
                        sql => sql.MigrationsAssembly(migrationsAssembly));
            })
            // this adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                    builder.UseSqlServer(connectionString,
                        sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup = true;
                options.TokenCleanupInterval = 30;
            });

        services.AddAuthentication()
            .AddGoogle("Google", options =>
            {
                options.ClientId = "434483408261-55tc8n0cs4ff1fe21ea8df2o443v2iuc.apps.googleusercontent.com";
                options.ClientSecret = "3gcoTrEDPPJ0ukn_aYYT6PWo";
            })
            .AddOpenIdConnect("oidc", "OpenID Connect", options =>
            {
                options.Authority = "https://demo.identityserver.io/";
                options.ClientId = "implicit";
                options.SaveTokens = true;

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                };
            });
    }

What do I miss here?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.387511 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO