© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
1 reply
gio735

✅ 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.AddAuthentication
services.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.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ builder.Services.AddDbContext<>
C#CC# / help
3y ago
Read-only question
C#CC# / help
2y ago
DI: Registration of services through a builder.
C#CC# / help
2y ago
API Architecture (CQRS, Read-Only repository, ...)
C#CC# / help
2y ago