I have a WebAPI 2 project that uses a token issued by the IdentityServer3 token provider. In my Startup.cs file, I have implemented the IdentityServerBearerTokenAuthorization middleware, and it, together with the global filter AuthorizateAttribute, requires a valid token in the request. However, I also added ClaimsTransformation so that I can extract “roles” from claims in a token issued using an implicit stream or a token issued for a client credential stream. I can’t use the scope here because I have 1 scope that gives you access to use my API, but all clients are not allowed to use all api endpoints.
Startup.cs
JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions()
{
Authority = ConfigurationManager.AppSettings["IdentityServer"],
RequiredScopes = new[] { "my.api" },
});
httpConfig.MapHttpAttributeRoutes();
httpConfig.Filters.Add(new AuthorizeAttribute());
app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(httpConfig);
app.UseWebApi(httpConfig);
app.UseClaimsTransformation(identity =>
{
var principal = new ClaimsPrincipal(identity);
if (!identity.HasClaim(c => c.Type == "name") && identity.HasClaim(c => c.Type == "client_name"))
{
identity.Identities.First().AddClaim(new Claim("name", identity.Claims.First(c => c.Type == "client_name").Value));
}
if (identity.Claims.Any(c => c.Type.Contains("client_")))
{
foreach (var claim in identity.Claims.Where(c => c.Type.Contains("client_")))
{
var newClaimType = claim.Type.Replace("client_", "");
identity.Identities.First().AddClaim(new Claim(newClaimType, claim.Value));
}
}
if (identity.Claims.Any(c => c.Type == "scope"))
{
identity.Identities.First().AddClaims(identity.Claims.Where(c => c.Type == "scope").Select(c => new Claim("role", c.Value)));
}
return Task.FromResult(principal);
});
APIController Authorize Roles. Authorize , . - ? \
API-
[HttpDelete]
[Authorize(Roles = "item.deleter")]
[Route("{itemId:guid}")]
public async Task<HttpResponseMessage> DeleteAsync([ValidGuid] Guid itemId)
{
_log.Audit.Info($"Received Delete request for item {itemId} from user {User.Identity?.Name}.");
if (!ModelState.IsValid)
....