C
C#8mo 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;
}
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.'
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.
1 Reply
gio735
gio735OP8mo ago
Sorry~ was using it after builder.Build() apparently...
Want results from more Discord servers?
Add your server