Niko Dierickx
Niko Dierickx

Reputation: 161

Identity server claims asp.net API

I'm currently writing an angular application that first authenticates against think texture identityserver3. This works fine, and I receive the bearer token without any issues. When I use my token on an call to my API, I'm authenticated. I can see my userid, but have lost my claims (username, roles,...). What do I have to do for transferring my claims with my token, or getting the roles from the identityserver?

Upvotes: 0

Views: 564

Answers (2)

Scott Brady
Scott Brady

Reputation: 5598

You can tell Identity Server to include specific claims in an access token by adding that claim to your API's Scope.

Example:

var apiScope = new Scope {
    Name = "myApi",
    DisplayName = "My API",
    Type = ScopeType.Resource,
    Claims = new List<ScopeClaim> {
        new ScopeClaim("myClaimType")
    }
};

You can also use the AlwaysIncludeInIdToken property of ScopeClaim to include the claims in identity tokens as well as access tokens.

See https://identityserver.github.io/Documentation/docsv2/configuration/scopesAndClaims.html for more info.

Upvotes: 1

Noel
Noel

Reputation: 600

We are doing something very similar using MS Web API 2 and a Thinktecture Identity Server v3.

To verify the user's claims we created an Authentication Filter, and then called the Identity server directly to get the user's claims. The bearer token only grants authentication and it is up to the API to get the claims separately.

protected override bool IsAuthorized(HttpActionContext actionContext)
    {
      string identityServerUrl = WebConfigurationManager.AppSettings.Get("IdentityServerUrl") + "/connect/userinfo";

      using (var httpClient = new HttpClient())
      {
        httpClient.DefaultRequestHeaders.Authorization = actionContext.Request.Headers.Authorization;

        var response = httpClient.GetAsync(identityServerUrl).Result;
        if (response.IsSuccessStatusCode)
        {
          string responseString = response.Content.ReadAsStringAsync().Result;
              Dictionary<string, string> claims = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString.ToLower());
          ... Do stuff with your claims here ...
        }
    }
}

Upvotes: 0

Related Questions