Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added a check for AllowAnonymous on the custom authorize attribute #2

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Helpers/AuthorizeAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,31 @@
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)]
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)
{
Expand Down
4 changes: 3 additions & 1 deletion Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AppSettings>(Configuration.GetSection("AppSettings"));
Expand Down