leo
leo

Reputation: 591

IdentityServer ASP.net CORE MVC ValidAudiences and Role is not working

I have a .net core MVC application, below are my queries

TargetFramework --> "net5.0"

IdentityModel Version--> "5.1.0"

Q1) In which I uses ValidAudiences which is not working. If I use ValidAudience token validation is working fine

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();


            //START for the cookie token based authentication
            JwtSecurityTokenHandler.DefaultMapInboundClaims = false;

            //Log Single Logout
            services.AddTransient<CookieEventHandler>();
            services.AddSingleton<LogoutSessionManager>();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = "oidc";
            })
                .AddCookie(options =>
                {
                    options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
                    options.Cookie.Name = "mvc31_";

                    options.EventsType = typeof(CookieEventHandler);
                })
                .AddOpenIdConnect("oidc", options =>
                {
                    options.Authority = "https://localhost:5001";
                    
                    options.ClientId = "testmvc31";
                    options.ClientSecret = "secret";
                    options.ResponseType = "code";

                    options.SaveTokens = true;

                    options.Scope.Clear();
                    options.Scope.Add("openid");
                    options.Scope.Add("profile");
                    options.Scope.Add("roles");

                    //adding api1 scope to access api
                    options.Scope.Add("api1");
                    options.Scope.Add("offline_access");

                    options.GetClaimsFromUserInfoEndpoint = true;

                    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                    {
                        //NameClaimType = JwtClaimTypes.Name,
                        RoleClaimType = "role",
                        ValidateIssuer = true,
                        ValidAudience = "testmvc31", //"testResource",
                        //ValidAudiences = new[] { "testResource1" }, //not working
                        ValidateAudience = true,
                    };
                });
            //END for the cookie token based authentication


        }

ValidAudiences suppose to work. Do you have any idea why its not working?

Q2) In Token validation I mentioned that Role is attached to the claims name "role", In access_token I case see the role claims value, But I can not see role claim in User.Claims.ToList() and User.IsInRole("admin") is false ?

options.GetClaimsFromUserInfoEndpoint = true;
    options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                        {
                            NameClaimType = JwtClaimTypes.Name,
                            RoleClaimType = JwtClaimTypes.Role,
                            ValidateIssuer = true,
                            ValidAudience = "testResource1"
                            //ValidAudiences = new[] { "testResource1" },
                            ValidateAudience = true,
                        };

Access_token

eyJhbGciOiJSUzI1NiIsImtpZCI6IjIwMUY0QzVCMzRFNzA3QzhDOTBGNEFFMDgyMkNDRDMxNEZENjlFMzBSUzI1NiIsInR5cCI6IkpXVCIsIng1dCI6IklCOU1XelRuQjhqSkQwcmdnaXpOTVVfV25qQSJ9.eyJuYmYiOjE2MjI2OTg3ODEsImV4cCI6MTYyMjcwMjM4MSwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NTAwMSIsImF1ZCI6WyJUZXN0QVBJMSIsIlRlc3RBUEkyVGVzdCIsImh0dHBzOi8vbG9jYWxob3N0OjUwMDEvcmVzb3VyY2VzIl0sImNsaWVudF9pZCI6InRlc3RtdmMzMSIsInN1YiI6ImQ4NjBlZmNhLTIyZDktNDdmZC04MjQ5LTc5MWJhNjFiMDdjNyIsImF1dGhfdGltZSI6MTYyMjY5ODc4MSwiaWRwIjoibG9jYWwiLCJyb2xlIjoiYWRtaW4iLCJqdGkiOiI0MkYyRTNEOEY3MkQ5NDQxMDAwQTdCMEI3Q0UyRTA0QSIsInNpZCI6IkE4QzVCMTRDQzgxMTc3RDFFRDlGRDdEQzVGNkZEMEY1IiwiaWF0IjoxNjIyNjk4NzgxLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwicm9sZXMiLCJhcGkxIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbInB3ZCJdfQ.dA4JOxeWd0cGlzr5BSANNL3ZZATzxchgFwLivQVH4rbyfPr6LRIvep6-NjrNEOL_YvJVCDIEU7TBC0-9qBZVL6OgmjDZBZ5dapNhD8ZZP39bUnfqXLJqRAQgR3yeIlB60EQ3vDEnLen1HZuZJCDoqzXr-sANp75IEOLYPxfDFE5SCljex_zX9AQ1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wzjUE925UOMrWgnyWQAVCuVZ-7W2nO3pkLhf5NW0ItUcF5I6TJn54wgcga-JP1rNh2gIIMT4N9ijfcdbbLVrX6wFqKlXEUWOzGW9m8A8oCZ5ZvbJ_iy3mNT-H3DjMO6K-FP2hwNeU7X3nhdvdrVM6_CyvfLQr9bHQVQB9Aj42DAFOQCfR4V2NtNQ

Any idea about this two issues?

Upvotes: 0

Views: 793

Answers (1)

Tore Nestenius
Tore Nestenius

Reputation: 19901

ValidAudiences in your API must match the aud claim in the access token.

You need to use for example:

ValidAudience = "testAPI"

For the role issue, can you paste a compelte sample access token?

Usually, you need to tell AddJwtBearer the name of your role claim, using:

 opt.TokenValidationParameters.RoleClaimType = "role";
 opt.TokenValidationParameters.NameClaimType = "name";

Similar to what you have done, so that should work.

Are you sure your role claim in the token is role, not roles?

The access token is not meant to be consumed or inspected by the client application, its only to be consumed by the API. The ID-token is used to create the "user" in the client ASP.NET Core application.

To get user claims into it, its just a matter to add them as a userclaims, like:

new IdentityResource(name: "employee", userClaims: new string[] { "role", "employeetype", "IsCeo" })  

Don't worry if you don't see the role in the IDToken,it will otherwise be retrieved from the UserInfo in a separate requests.

You control this using this flag in the Client definition:

// When requesting both an id token and access token, should the user claims always
// be added to the id token instead of requiring the client to use the UserInfo endpoint.
// Defaults to false.
AlwaysIncludeUserClaimsInIdToken = false,

In AddOpenIDConnect you also have this flag:

options.GetClaimsFromUserInfoEndpoint = true;

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

Upvotes: 0

Related Questions