diff --git a/Helpers/AuthorizeAttribute.cs b/Helpers/AuthorizeAttribute.cs index deb4b5d..68de066 100644 --- a/Helpers/AuthorizeAttribute.cs +++ b/Helpers/AuthorizeAttribute.cs @@ -2,6 +2,9 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System; +using System.Linq; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc.Controllers; using WebApi.Entities; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] @@ -9,6 +12,21 @@ public class AuthorizeAttribute : Attribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { + // We're checking here to see if the route has been decorated with an [AllowAnonymous] attribute. If it has, we skip authorization + // for the route. Doing this allows us to apply the [Authorize] attribute by default in the startup using: + // + // services.AddControllers().AddMvcOptions(x => x.Filters.Add(new AuthorizeAttribute())) + // + if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor) + { + var hasAllowAnonymousAttribute = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true) + .Any(a => a.GetType() == typeof(AllowAnonymousAttribute)); + if (hasAllowAnonymousAttribute) + { + return; + } + } + var user = (User)context.HttpContext.Items["User"]; if (user == null) { diff --git a/Startup.cs b/Startup.cs index 71e0d8e..b5b9a83 100644 --- a/Startup.cs +++ b/Startup.cs @@ -20,7 +20,9 @@ public Startup(IConfiguration configuration) public void ConfigureServices(IServiceCollection services) { services.AddCors(); - services.AddControllers(); + services.AddControllers() + //.AddMvcOptions(x => x.Filters.Add(new AuthorizeAttribute())) //Uncomment this line to add the authorize attribute to all route by default + ; // configure strongly typed settings object services.Configure(Configuration.GetSection("AppSettings"));