Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Blazor server app with API, redirecting to Login page

$
0
0

I have a .NET 8 Blazor server app with identity individual accounts. program.cs is as follows:

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");        app.UseHsts();    }    app.UseHttpsRedirection();    app.UseStaticFiles();    app.UseAntiforgery();    app.MapRazorComponents<App>()        .AddInteractiveServerRenderMode();    // Add additional endpoints required by the Identity /Account Razor components.    app.MapAdditionalIdentityEndpoints();    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();}

Using Postman or another app, I can login:

private async Task OnValidSubmit(){    // login to license server and get token    var response = await http.PostAsJsonAsync("https://localhost:44325/login", model); //this uses the injected client    if (!response.IsSuccessStatusCode)    {        Snackbar.Add("License could not be saved.", Severity.Error);    }    AccessTokenResponse tokens;    tokens = response.Content.ReadFromJsonAsync<AccessTokenResponse>().Result;    // create a new client because we will be changing its auth header to connect to license server API.    var httpClient = new HttpClient();    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokens.AccessToken.ToString());    success = false;    HttpResponseMessage respon = await httpClient.GetAsync($"https://localhost:44325/api/License/GetLicense/{email}/{product_name}");    if (respon.IsSuccessStatusCode)    {        var jsonResponse = await respon.Content.ReadAsStringAsync(); //I am returned Login page here instead of my data.        var license = JsonSerializer.Deserialize<License>(jsonResponse);        string licenseKey = Microsoft.IdentityModel.Tokens.Base64UrlEncoder.Encode(license.ToString());        var res = await DataService2.SaveLicense(licenseKey);        if (res)        {            Snackbar.Add("License saved successfully.", Severity.Success);        }        else        {            Snackbar.Add("License could not be saved.", Severity.Error);        }    }    success = true;}

In the above code, after successful login, I get the bearer token in tokens. I then make a new http client and set its authorization header and then call the API. However, when I make the API call, instead of hitting the API, I am returned with the Login page of the Blazor server app. Why would an API call result in Login page response instead of my own data from the API? Looks like Blazor routing is somehow taking precedence over the API call and my http request is being routed to the Blazor project instead of the API project. But the first Login request is successful.

Any idea why the API is not being hit and instead I am receiving the Login page?


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>