Skip to content

Instantly share code, notes, and snippets.

@vquaiato
Created October 7, 2016 12:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vquaiato/9e4640b9172cf7ec1546fa7b8518e15b to your computer and use it in GitHub Desktop.
Save vquaiato/9e4640b9172cf7ec1546fa7b8518e15b to your computer and use it in GitHub Desktop.
Extension for ASP.NET Core Startup to return 401 on unauthorized API calls
public static IApplicationBuilder Use401ForUnauthorizedApiCalls(this IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
if (context.Request.Path.Value.Contains("/api") &&
(context.User == null ||
context.User.Identity == null ||
!context.User.Identity.IsAuthenticated))
{
context.Response.StatusCode = 401;
return;
}
await next();
});
return app;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment