Keycloak与ASP.NET 5 API服务集成问题求助:Bearer Token验证异常
Hey there, let's break down what's going on with your Keycloak and ASP.NET 5 integration issue, and fix it step by step.
The Core Problem
When you set options.ApiName = "account" and validation passes without needing the client secret, that's because "account" is a built-in Keycloak client (used for Keycloak's own admin endpoints), not your custom "api" client. The JWT's aud (audience) claim is set to "account" by default, so when you match that value, the authentication middleware doesn't check for a client secret—since it's not validating against your confidential API client.
How to Fix It
The root issue is that your "api" client isn't configured properly in Keycloak to be recognized as a resource server, so the access tokens issued don't include your client ID in the aud claim. Here's what you need to do:
1. Configure Your "api" Client in Keycloak
- Log into your Keycloak admin console, navigate to your realm, and go to Clients > api
- In the Settings tab:
- Set Access Type to
confidential(this enforces the need for a client secret) - Save the changes
- Set Access Type to
- Switch to the Mappers tab:
- Click Create to add a new mapper
- Set Name to something like
api-audience - Set Mapper Type to
Audience - Under Included Client Audience, select your "api" client ID from the dropdown
- Check both Add to ID token and Add to access token (at minimum, ensure the access token option is checked)
- Save the mapper
2. Update Your ASP.NET 5 Authentication Code
Now that Keycloak will include "api" in the JWT's aud claim, you can update your code to validate against your actual API client:
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = $"{Configuration["Authentication:KeycloakAuthentication:ServerAddress"]}/auth/realms/{Configuration["Authentication:KeycloakAuthentication:Realm"]}"; // Now use your actual client ID as ApiName options.ApiName = "api"; options.ApiSecret = Configuration["Authentication:KeycloakAuthentication:ClientSecret"]; options.EnableCaching = true; options.RequireHttpsMetadata = false; }) .AddCookie(options => { options.ExpireTimeSpan = TimeSpan.FromMinutes(60); options.Cookie.Name = "api.cookie"; });
3. Verify the JWT
After making these changes, log in via your Angular app, grab the access token, and parse it using a tool like jwt.io. You should now see your "api" client ID listed in the aud claim array alongside "account".
Additional Notes
- Make sure your Angular app is requesting and sending the access token (not the ID token) to your API—access tokens are designed for resource server validation, while ID tokens are for client-side authentication.
- Double-check that the client secret in your ASP.NET config matches the one found in Keycloak's Clients > api > Credentials tab (it's the value under "Secret").
内容的提问来源于stack exchange,提问作者Brad

