Dogs Chasing Squirrels

A software development blog

Adding roles to IdentityServer4 OpenID Results

0

The IdentityServer4 Quickstart projects make it look so easy to add new custom properties to identity users. In their sample, they just add a “website” claim to a user and it shows up in the client. Easy!

new TestUser {
    SubjectId = "1",
    Username = "alice",
    Password = "password",

    Claims = new List<Claim> {
        new Claim("name", "Alice"),
        new Claim("website", "https://alice.com")
    }
},
User logged in
{
  "sid": "94ffdf2501942878493f60cc14291a83",
  "sub": "1",
  "auth_time": 1534264648,
  "idp": "local",
  "name": "Alice",
  "website": "https://alice.com",
  "amr": [
    "pwd"
  ]
}

And yet when I add a claim of my own, like “role” it’s nowhere to be seen.

    Claims = new List<Claim> {
        new Claim("name", "Alice"),
        new Claim("website", "https://alice.com"),
        new Claim("role", "admin")
    }
},

What’s going on???

Well, it turns out that “website” is already in the list of standard profile claims. Role is not. So what do we need to do to add it?

First of all, if we want the claim to show up in the JavaScript client and not in the API then we want to create a Identity Resource not an Api Resource.

public static IEnumerable<IdentityResource> GetIdentityResources() => new List<IdentityResource> {
    new IdentityResources.OpenId(),
    new IdentityResources.Profile(),
    new IdentityResource( "roles", new [] { "role" } )
};

And then have the client request it:

var config = {
    authority: "http://localhost:5000",
    client_id: "js",
    redirect_uri: "http://localhost:5003/callback.html",
    response_type: "id_token token",
    scope:"openid profile api1 roles",
    post_logout_redirect_uri : "http://localhost:5003/index.html",
};

Then it shows up in the client:

User logged in
{
  "sid": "94ffdf2501942878493f60cc14291a83",
  "sub": "1",
  "auth_time": 1534264648,
  "idp": "local",
  "name": "Alice",
  "website": "https://alice.com",
  "role": "Admin",
  "amr": [
    "pwd"
  ]
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: