Search code examples
asp.net-coreidentityserver4claims-based-identity

How to define role Identity resource in appsettings.json in Asp.net core


I have created an asp.net core web application with individual accounts security and configure it to be used for authorization/authentication of the external spa i have added following configuration in appset5tings.json file

 {
 "ConnectionStrings": 
{
"DefaultConnection": 
 "Server=localhost;Database=itrSts;Trusted_Connection=True;MultipleActiveResultSets=true"
 },
"Logging": {
"LogLevel": {
  "Default": "Information",
  "Microsoft": "Warning",
  "Microsoft.Hosting.Lifetime": "Information"
}
},
 "IdentityServer": {
"Clients": {
  "itr.childcare.webapp": {
    "Profile": "SPA",
    "RedirectUri": "http://localhost:3000/signin-callback",
    "LogoutUri": "http://localhost:3000/signout-callback",
    "AccessTokenLifetime": 600,
    "Scopes": "openid profile gateway-api roles"

  },
  "Itr.Sts": {
    "Profile": "IdentityServerSPA"
  }

}
"Resources": {
  "gateway-api": {
    "Profile": "API",
    "UserClaims": [
      "role"
    ]
  }

}

} }

It works fine when "openid profile gateway-api" scopes are requested but when roles scope is also requested i get invalid scope error can anyone help me and tell what should i should do? Thanks


Solution

  • What is missing is the Identity Resource definitions. They define what claims (including Roles) that should be available to the clients.

    See this article about Identity Resources.

    If you are using IdentityServer4, version 4.x, then you should also look into defining ApiScopes.

    In code, the definition for IdentityResources can look like this:

    var employeeInfoScope = new IdentityResource()
    {
        Name = "employee_info",
        DisplayName = "Employee information",
        Description = "Employee information including seniority and status...",
        Emphasize = true,
        Enabled = true,
        Required = true,
        ShowInDiscoveryDocument = true,
        UserClaims = new List<string>
        {
            "employment_start",
            "seniority",
            "contractor",
            "employee",
        }
    };
    
    _identityResources = new List<IdentityResource>()
    {
        new IdentityResources.OpenId(),
        new IdentityResources.Email(),
        new IdentityResources.Profile(),
        new IdentityResources.Address(),
        employeeInfoScope
    };
    

    To complement this answer, I wrote a blog post that goes into more detail about this topic: IdentityServer – IdentityResource vs. ApiResource vs. ApiScope