Skip to content

Instantly share code, notes, and snippets.

@HamidMolareza
Last active October 4, 2023 06:49
Show Gist options
  • Save HamidMolareza/e31f3aa2e4dad0667d227f2c998f283e to your computer and use it in GitHub Desktop.
Save HamidMolareza/e31f3aa2e4dad0667d227f2c998f283e to your computer and use it in GitHub Desktop.
Returns 401 error code when user is not authorized in ASP MVC or Razor Pages
public class ApiAuthorizeAttribute : TypeFilterAttribute {
public ApiAuthorizeAttribute() : base(typeof(ApiAuthorizeFilter)) {
}
}
public class ApiAuthorizeFilter : IAuthorizationFilter {
public void OnAuthorization(AuthorizationFilterContext context) {
if (context.HttpContext.User.Identity is not null &&
!context.HttpContext.User.Identity.IsAuthenticated) {
// Return a 401 Unauthorized status code
context.Result = new UnauthorizedResult();
}
}
}
//TODO: Do not forget to add the service to the Program.cs
//builder.Services.AddScoped<ApiAuthorizeFilter>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment