In my ASP.NET Core 3.1 - Angular 9 web app, this is my pipelilne:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseExceptionHandler(GlobalExceptions.WebApiExceptionHandler(
exposeExceptionDetailsToHttp: env.IsDevelopment() || env.EnvironmentName == DssEnvironment.AutomatedTesting,
logger: Serilog.Log.Logger
));
if (!(env.IsDevelopment())
{
app.UseHsts();
}
app.UseRouting();
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
app.UseWhen(
httpContext => !httpContext.Request.Path.Value.StartsWith("/api"),
appBranch =>
{
appBranch.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
spa.Options.StartupTimeout = new TimeSpan(0, 5, 0);
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
);
}
The angular front end would use the authentication token to authorize access to the various routes, these are all working properly.
The issue: my backend controllers use the standard 'api/{controller}/{action}
' path, they are properly protected in the sense that if one types an api call directly into browser URL address bar, it will immediately come back with 401 error without executing the endpoint. But what I want to do is to redirect to the main page that has a login section. I've searched and experimented a lot of ways, couldn't get it to work.
My angular front end has an interceptor that detects 401/403 error, but it doesn't intercept if it is from an api endpoint path that is typed directly into browser address bar.
I also tried to use the auth guard on 'api...' path, but it is not hitting it as the SPA path is defined for when
!httpContext.Request.Path.Value.StartsWith("/api")
on the backend, obviously these api endpoints are already protected through the pipeline UseAuthentication()
and I don't see a way in either UseRouting
or UseEndpoints
middleware where I can configure a redirect.
So I am really at a lost about how to handle the redirect when an api call is typed into the browser's URL address bar directly.
(as a side note: it doesn't appear that the http pipeline can be debugged/stepped through at runtime, e.g. when calling each api endpoint, which would be great for understanding the processes).
You will get 401 error when you directly call api from url. You can use Swashbuckle to avoid the problem. Here is a link:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-6.0&tabs=visual-studio