You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I added a controller to the .NET 8 Blazor server project to accept API calls. When I call the controller API without authorize attribute, I get my desired data. When I use the [Authorize] attribute, I get redirected to the Login page instead of receiving a reply from the API. Why is this happening? Even if I am not authenticated (the http request does not contain the Authorization header), the API should respond and I should get a NotFound error, not a 200 Ok response along with the Login page. It does not matter if my http request contains Authorization header with a valid token or not, the result is the same. Here is my program.cs:
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(); //added for API
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<IdentityUserAccessor>();
builder.Services.AddScoped<IdentityRedirectManager>();
builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddBearerToken(IdentityConstants.BearerScheme)
.AddIdentityCookies();
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
//builder.Services.AddDbContextFactory<ApplicationDbContext>(options =>
// options.UseSqlServer(connectionString));
builder.Services.AddDbContextFactory<ApplicationDbContext>(options =>
options.UseMySql(connectionString, new MySqlServerVersion(new Version(8, 0, 26)),
mySqlOptions =>
{
mySqlOptions
.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(30),
errorNumbersToAdd: null);
}
)
.EnableSensitiveDataLogging(true));//should be scoped as ApplicationDbContext uses the TenantDbContext which is also scoped. By default the service is Singleton
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddSignInManager()
.AddDefaultTokenProviders();
builder.Services.AddSingleton<IEmailSender<ApplicationUser>, EmailSender>();
builder.Services.AddSingleton<RegistrationDataSaver>();
builder.Services.AddAuthorization(); //added for API
builder.Services.AddEndpointsApiExplorer(); //Added for API
builder.Services.AddSwaggerGen(); //Added for API
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
// Inside the ConfigureServices method
builder.Services.AddHttpClient();
builder.Services.AddMudServices();
var app = builder.Build();
app.MapControllers(); //added for API
app.MyMapIdentityApi<ApplicationUser>();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
app.UseSwagger(); //added for API
app.UseSwaggerUI(); //added for API
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
// Add additional endpoints required by the Identity /Account Razor components.
app.MapAdditionalIdentityEndpoints();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.UseAuthorization();//added for API
app.UseCors(policy =>
policy.WithOrigins("http://localhost:7217", "https://localhost:7217")
.AllowAnyMethod()
.WithHeaders(HeaderNames.ContentType, HeaderNames.Authorization,
"x-custom-header")
.AllowCredentials()
);
app.Run();
}
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
I added a controller to the .NET 8 Blazor server project to accept API calls. When I call the controller API without authorize attribute, I get my desired data. When I use the [Authorize] attribute, I get redirected to the Login page instead of receiving a reply from the API. Why is this happening? Even if I am not authenticated (the http request does not contain the Authorization header), the API should respond and I should get a NotFound error, not a 200 Ok response along with the Login page. It does not matter if my http request contains Authorization header with a valid token or not, the result is the same. Here is my program.cs:
Beta Was this translation helpful? Give feedback.
All reactions