0

I have inherited an ASP.NET Core 5 MVC application that has integrated the authentication of the users with a third-party identity server, WSO2.

The authentication is working fine, but I'm not able to understand how to retrieve the username of the user that has logged in.

Here is the code:

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddSession();
    services.AddControllersWithViews();
    services.AddTransient<IUserRepository, UserRepository>();
    services.AddTransient<ITokenService, TokenService>();

    services.AddAuthentication(auth =>
    {
        auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        //auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
        };
    });

    services.AddHttpClient();
}

in the controller I have added:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = "Administrator,Supervisor")]

Giox
  • 4,785
  • 8
  • 38
  • 81
  • Where in the application do you want to fetch the username? In a Controller? – Daniel Stackenland Dec 02 '21 at 09:39
  • Does this answer your question? [How to get the current user in ASP.NET MVC](https://stackoverflow.com/questions/263486/how-to-get-the-current-user-in-asp-net-mvc) – Crowcoder Dec 02 '21 at 09:40
  • @DanielStackenland yes exactly, in the controller – Giox Dec 02 '21 at 10:06
  • @Crowcoder No, it's different as they are using identity with "local" authentication, so they don't use JWT/OAuth2/OIDC. Thanks – Giox Dec 02 '21 at 10:13

1 Answers1

0

Is the name and roles found in the JWT token?

If, so then the issue is that OpenIDConnect and Microsoft do not agree about what the name of the 'name' claim should be.

To address this, you need to tell AddJwtBearer, which claim is the 'name' and 'role' claim using:

.AddJwtBearer(opt =>
    {
        ...
        opt.TokenValidationParameters.RoleClaimType = "roles";
        opt.TokenValidationParameters.NameClaimType = "name";

To complement this answer, I wrote a blog post that goes into more detail about this topic: Debugging OpenID Connect claim problems in ASP.NET Core and about JwtBearer claim problems here.

Tore Nestenius
  • 16,431
  • 5
  • 30
  • 40