✅ read-only builder.Services
public static IServiceCollection AddTokenAuthentication(this IServiceCollection services, string key)
{
var keybytes = Encoding.ASCII.GetBytes(key);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
x.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(keybytes),
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = "localhost",
ValidAudience = "localhost"
});
return services;
}public static IServiceCollection AddTokenAuthentication(this IServiceCollection services, string key)
{
var keybytes = Encoding.ASCII.GetBytes(key);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
x.TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new SymmetricSecurityKey(keybytes),
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = "localhost",
ValidAudience = "localhost"
});
return services;
}services.AddAuthenticationservices.AddAuthentication throws exception: System.InvalidOperationException: 'The service collection cannot be modified because it is read-only.'System.InvalidOperationException: 'The service collection cannot be modified because it is read-only.'this exact approach works for API, in MVC project I'm planning to inject token into header through middleware.