Created
October 7, 2016 12:41
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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