Jason Chan
Jason Chan

Reputation: 315

How to add logging for unauthorized access for [Authorize] filter in webapi

I created an ASP.NET Web API 2 end point, with controllers protected with the [Authorized] attribute.

Unauthenticated access will get 401 UnAuthorized http status.

Now, I want to log those unauthorized access to a log file. However, I don't know where to handle the unauthorized access.

Upvotes: 3

Views: 2165

Answers (1)

Benjamin Soulier
Benjamin Soulier

Reputation: 2263

The solution would just be to create a custom Authorize filter inheriting from default Authorize attribute this way:

public class LogAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        var authorized = base.IsAuthorized(actionContext);
        if (!authorized)
        {
            // log the denied access attempt.
        }
        return authorized;
    }
}

This way, you keep the same authorize validation from parent, but you can do additional thing such as logging in your case for unauthorized access.

You can then simply use it on your Web API methods:

public class ValuesController : ApiController
{
    [LogAuthorize]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}

Upvotes: 4

Related Questions