User gets access to a wrong account
We use IdentityServer4 in our application. We are faced with a situation where one user gets access to the wrong account. We believe that it happens during getting the access token by the refresh token. But we have no idea how to reproduce it. We found that some of users have two access tokens for this client in the table dbo.PersistedGrants.
Our configuration. We have IdentityServer4 on the AKS Kubernetes cluster with the ingress controller and via https protocol. We also added a custom token hash calculation to allow using our token data from previous IdentityServer3.
// Client configuration
var client = new Client()
{
ClientId = "app",
ClientName = "App",
AbsoluteRefreshTokenLifetime = 0,
AccessTokenLifetime = 3600,
AccessTokenType = AccessTokenType.Jwt,
AllowOfflineAccess = true,
RefreshTokenUsage = TokenUsage.ReUse,
RefreshTokenExpiration = TokenExpiration.Sliding,
RequireConsent = false,
SlidingRefreshTokenLifetime = 1296000,
AllowedCorsOrigins = new[] {
"http://127.0.0.1:886",
"http://127.0.0.1:20456",
"http://127.0.0.1:35413"
},
AllowedGrantTypes = new[] {
"authorization_code",
"refresh_token"
},
AllowedScopes = new[] {
"main_api",
"openid",
"profile",
"email",
"offline_access"
},
ClientSecrets = new[] {
new Secret() {Value = "..." }
},
RedirectUris = new[] {
"http://127.0.0.1:886",
"http://127.0.0.1:20456",
"http://127.0.0.1:35413"
}
};
// Application configuration
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ApplicationIdentity")));
ConfigureAspIdentity(services);
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = Configuration["ServiceLinks:AuthorizationServerUrl"] + "/" + AppConstants.ServerRoot;
options.RequireHttpsMetadata = false; // in the production environment the secure connection is provided by the NGNIX ingress controller
options.ApiName = AppConstants.IdentityApiScope;
});
services.AddAntiforgery(options =>
{
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
services.AddMvc();
ConfigureIdentityServer(services);
services.AddTransient<I18nMiddleware>();
services.AddTransient<CookieMiddleware>(); // Cleanup old cookies
services.AddTransient<ExceptionMiddleware>(); // Returning error with json content
services.AddSingleton<RecaptchaService>();
RazorEngineHelper.Initialize(AppSettings.ServiceLinks, typeof(Startup).Assembly, typeof(Startup).Namespace);
}
private void ConfigureAspIdentity(IServiceCollection services)
{
// User registration parameters
var builder = services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
// Custom provider for email to expand token expiration time
options.Tokens.EmailConfirmationTokenProvider = nameof(ConfirmEmailDataProtectorTokenProvider);
});
builder.AddErrorDescriber<CustomIdentityErrorDescriber>();
// Store the operational data in DB
builder.AddEntityFrameworkStores<ApplicationDbContext>();
// Token providers
builder.AddDefaultTokenProviders();
builder.AddTokenProvider<ConfirmEmailDataProtectorTokenProvider>(nameof(ConfirmEmailDataProtectorTokenProvider));
}
private void ConfigureIdentityServer(IServiceCollection services)
{
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
// configure identity server with in-memory stores, keys, clients and scopes
IIdentityServerBuilder builder = services.AddIdentityServer(options =>
{
// Disable idsrv.session cookie
options.Endpoints.EnableCheckSessionEndpoint = false;
// Identity Server address
options.PublicOrigin = Configuration["ServiceLinks:AuthorizationServerUrl"];
});
// Add scopes that define the resources in system
builder.AddInMemoryIdentityResources(
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Email(),
new IdentityResources.Profile()
});
// Add custom APIs
var apiResources = Configuration.GetSection("ApiResources").Get<ApiResource[]>();
var secret = apiResources.First(a => a.Name == AppConstants.MainApiScope).ApiSecrets.First();
secret.Value = secret.Value.Sha256();
builder.AddInMemoryApiResources(apiResources);
// Add clients
builder.AddInMemoryClients(Clients.Get(Configuration));
// Configures IdentityServer to use the ASP.NET Identity implementations
builder.AddAspNetIdentity<ApplicationUser>();
// Store the operational data in DB (codes, tokens, consents)
builder.AddOperationalStore(options =>
{
options.ConfigureDbContext = b =>
b.UseSqlServer(Configuration.GetConnectionString("ApplicationIdentity"),
sql => sql.MigrationsAssembly(GetType().GetTypeInfo().Assembly.GetName().Name));
// Enable automatic token cleanup (removing expired grants)
options.EnableTokenCleanup = true;
});
// Add certificares
builder.AddSigningCredential(Certificate.Load());
// Replace hash code calculate algorithm to allow compatibility with IdentityServer3 database data
builder.Services.AddTransient<IRefreshTokenStore, IdentityServerCustomization.CustomRefreshTokenStore>();
builder.Services.AddTransient<IReferenceTokenStore, IdentityServerCustomization.CustomReferenceTokenStore>();
builder.Services.AddTransient<IAuthorizationCodeStore, IdentityServerCustomization.CustomAuthorizationCodeStore>();
builder.Services.AddTransient<IUserConsentStore, IdentityServerCustomization.CustomUserConsentStore>();
// Catch registration
builder.Services.AddTransient<IAuthorizeInteractionResponseGenerator, IdentityServerCustomization.CustomAuthorizeInteractionResponseGenerator>();
// Custom validator for removing old API access tokens during issuing a new token
builder.Services.AddTransient<ITokenResponseGenerator, IdentityServerCustomization.CustomTokenResponseGenerator>();
// extension grant validators
builder.AddExtensionGrantValidator<SubjectGrantValidator>();
builder.AddExtensionGrantValidator<ExternalTokenGrantValidator>();
// Add custom claims
builder.AddProfileService<IdentityCustomization.CustomProfileService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder appplicationBuilder, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
appplicationBuilder.Map("/" + AppConstants.ServerRoot, app =>
{
loggerFactory.AddFile(Configuration.GetSection("Logging"));
var logger = loggerFactory.CreateLogger(GetType());
// Log debug information
PrintDebugInfo(app);
app.UseForwardedHeaders();
app.UseExceptionHandler("/" + AppConstants.ErrorAction);
app.UseMiddleware<I18nMiddleware>();
app.UseMiddleware<CookieMiddleware>();
app.UseMiddleware<ExceptionMiddleware>();
MigrationHelper.UpdateDatabase(app);
AllowCors(app); // TMET-1224
app.Use((context, next) =>
{
context.Request.Scheme = "https";
return next();
});
app.UseHttpMethodOverride();
app.UseIdentityServer();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "/{action=Index}/{id?}");
});
});
appplicationBuilder.UseStaticFiles();
}
// Custom tokeh hash calculation
internal static class CustomizationUtils
{
/// <summary>
/// Calculates key hash for the token table.
/// Replaced for allowing compatibility with IdentityServer3 data.
/// Code was copied from IdentityServer3.Core.Services.Default.KeyHashingTransientDataRepository.Hash method.
/// </summary>
public static string GetHashedKey(string value)
{
if (string.IsNullOrWhiteSpace(value)) throw new ArgumentNullException("value");
using (var hash = HashAlgorithm.Create("SHA256"))
{
var bytes = Encoding.UTF8.GetBytes(value);
var hashedBytes = hash.ComputeHash(bytes);
var hashedString = Base64Url.Encode(hashedBytes);
return hashedString;
}
}
}
internal class CustomRefreshTokenStore : DefaultRefreshTokenStore
{
public CustomRefreshTokenStore(IPersistedGrantStore store, IPersistentGrantSerializer serializer, IHandleGenerationService handleGenerationService, ILogger<DefaultRefreshTokenStore> logger)
: base(store, serializer, handleGenerationService, logger)
{
}
protected override string GetHashedKey(string value)
{
return CustomizationUtils.GetHashedKey(value);
}
}
internal class CustomReferenceTokenStore : DefaultReferenceTokenStore
{
public CustomReferenceTokenStore(IPersistedGrantStore store, IPersistentGrantSerializer serializer, IHandleGenerationService handleGenerationService, ILogger<DefaultReferenceTokenStore> logger)
: base(store, serializer, handleGenerationService, logger)
{
}
protected override string GetHashedKey(string value)
{
return CustomizationUtils.GetHashedKey(value);
}
}
internal class CustomAuthorizationCodeStore : DefaultAuthorizationCodeStore
{
public CustomAuthorizationCodeStore(IPersistedGrantStore store, IPersistentGrantSerializer serializer, IHandleGenerationService handleGenerationService, ILogger<DefaultAuthorizationCodeStore> logger)
: base(store, serializer, handleGenerationService, logger)
{
}
protected override string GetHashedKey(string value)
{
return CustomizationUtils.GetHashedKey(value);
}
}
internal class CustomUserConsentStore : DefaultUserConsentStore
{
public CustomUserConsentStore(IPersistedGrantStore store, IPersistentGrantSerializer serializer, IHandleGenerationService handleGenerationService, ILogger<DefaultUserConsentStore> logger)
: base(store, serializer, handleGenerationService, logger)
{
}
protected override string GetHashedKey(string value)
{
return CustomizationUtils.GetHashedKey(value);
}
}
We need more information - do you also have logs to get more insight?
There is a log for the previous few days. We usually have a lot of information in IdentityServer4 output, so we set LogLevel to 'Error'.
I also have to mention that our client has multiple instances and an internal http server.
Resolved via email.
Hi guys, i'm having the same problem as @KlausTrikk, can you share the solution for this @leastprivilege?
We could reproduce the problem with the OP. Have you done any custom implementations of stores e.g.?
I sent an email with more details to [email protected]
Many users still face the problem. It always happens after service restart. Upgrade from 2.5.4 to 3.1.3 did not solve the problem.
I am facing the same problem. IdentityServer4 + ASP.NET Core Identity. Access token is issued to different user.
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.