I'm having issue to call authorize api from react SPA. It's working if removed the [Authorize] attribute in the controller/action, but once added in the attribute, the response goes to SPA home page.
Project Structure
IdentityServer (.net core 3.1 mvc with IdentityServer4 *reference token type)
Login (authentication with IdentityServer and auth callback to Portal)
Portal (.net core 3.1 react SPA, use IdentityServer4.AccessTokenValidation to validate
react
fetch('/api/test').then(async (response) => {
var data = await response.json();
console.dir(response);
console.dir(data);
});
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddControllersWithViews()
.ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; });
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "https://localhost:44302";
options.ApiName = "api1";
options.ApiSecret = "thisissecret";
});
services.AddSpaStaticFiles(configuration => { configuration.RootPath = "ClientApp/build"; });
}
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); });
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (_WebHostEnvironment.IsDevelopment())
{
spa.UseReactDevelopmentServer("start");
}
});
}
Is worked if the api controller doesn't have the "Authorize" attribute, but once added in then will keep on unauthorized.