Access custom claim in ASP.NET Core

I am trying to access a custom claim in my sample application which is modeled around https://developer.okta.com/quickstart/#/okta-sign-in-page/dotnet/aspnetcore

I created a claim in the UI like this

viewing HttpContext.User.Claims. does not show me that claim. Can anybody point me in the right direction?

Does the new claim show up if you use the Token Preview panel to preview a request?

Hi nate, no it doesn’t.

Hey @jeffreyeas, sorry that your message got flagged here. The spam detector bot was overzealous. We’ve updated the settings to prevent this happening in the future. :slight_smile:

AspNetCore will automatically copy any claims that exist in the token into HttpContext.User.Claims. If it’s not showing up there, it probably doesn’t exist in the token - which is why I suggested the Token Preview feature as a sanity check.

Try updating the claim expression to: user.firstName - the claim won’t show up if the expression is invalid. You can double-check the correct spelling/case of a profile property in the Profile Editor.

thank you nate. I tried user.firstName and I can finally see the claim in the token preview. However, that token still doesn’t exist in User.Claims when I hover over it. Did I add the claim in the wrong place? I added it on the ‘access’ tab

These are the only claims that come back. Can someone please point me in the right direction?

http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier
name
jti
http://schemas.microsoft.com/claims/authnmethodsreferences
pwd
http://schemas.microsoft.com/identity/claims/identityprovider
preferred_username
given_name
family_name

Can you post your Startup.cs code?

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Okta.Sdk;
using Okta.Sdk.Configuration;


namespace OktaWebIntegration
{
    public class Startup
   {
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(sharedOptions =>
        {
            sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddOpenIdConnect(options =>
        {
            options.ClientId = "00000000000";
            options.ClientSecret = "ladeedadeee";
            options.Authority = "https://dev-291664-admin.oktapreview.com/oauth2/default";
            options.CallbackPath = "/authorization-code/callback";
            options.ResponseType = "code";
            options.SaveTokens = true;
            options.UseTokenLifetime = false;
            options.GetClaimsFromUserInfoEndpoint = true;
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name"
            };
        });

        services.AddSingleton<IOktaClient>
        (
            new OktaClient(new OktaClientConfiguration()
            {
                OrgUrl = Configuration["okta:OrgUrl"],
                Token = Configuration["okta:APIToken"]
            })
        );
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}
}

You should remove the -admin and change this to options.Authority = “https://dev-291664.oktapreview.com/oauth2/default”;

1 Like

Thanks. I did change it, I still see the same claims

That’s weird as I was able to get the firstName claim in the id_token. (Not in .net sample)

Can you change Scopes in the UI from profile to Any and try?
This was the configuration that worked for me -

Just tried it, not working either

any more suggestions?

Not sure what else might be going wrong.
Have you tried changing GetClaimsFromUserInfoEndpoint = true; to AlwaysIncludeUserClaimsInIdToken = true? (Refer - https://github.com/aspnet/Security/issues/1449#issuecomment-331954243)

@nate.barbettini - Any other suggestions?

That’s a link to identityserver. I am creating a client. And I don’t even see where to put AlwaysIncludeUserClaimsInIdToken. Is there any way I can zip this up and send to someone? i am working off of your sample and it does not explain how to return custom claims

Hi jeffreyeas,

I tried to reproduce your issue and I got it working with user.firstName.
But, I realized that the browser was caching the first value I set for the claim (“foobar”), so I had to try again in a new incognito window to see the new setting.
Make sure to have checked Authorization Code , Implicit (Hybrid) and Allow ID Token with implicit grant type in the general settings of your application.
If after this, you are still facing with this issue create a repo in GitHub and send me the link, I will be happy to take a look.

2 Likes

Can you just paste a screenshot of the above?

@laura.rodriguez nevermind, found it. I unchecked ‘Allow Access Token with implicit grant type’ and now get 16 claims other than the custom one.

Can you confirm that you got it working using the .net core sample application?