C#C
C#2y ago
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;
}


services.AddAuthentication throws exception:
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.
Was this page helpful?