Feisser
Feisser

Reputation: 21

MVC Controller, Action Filters not working

I want to add Bearer Authentication for the Controllers but it is not running the code from the Action Filter. I tried to add Debug.WriteLine(...); but it dont show anything in the output.

fetch:

fetch('api/Test/Select', {
   headers: {
      'Content-type': 'application/json',
      'Authorization': `Bearer ${sessionStorage.getItem("token")}`,
   },
   method: 'GET',
})

and the MVC Controller:

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;

namespace API
{
    [BearerAuthentication] //<-- Action Filter
    [Route("api/Test")]
    public class TestController : ControllerBase
    {
        //...

       [HttpGet("Select")]
       public IActionResult Select()
       {
           try
           {
              return Ok(FirstService.Select());
           }
           catch (Exception ex)
           {
              return Conflict(ex);
           }
       }
//...
        

Action Filter:

    public class BearerAuthenticationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext context)
        {
            Debug.WriteLine("Why are u not working?"); //<-- Debug Console shows nothing

            HttpRequestMessage request = context.Request;
            AuthenticationHeaderValue authorization = request.Headers.Authorization;

            //...
        }
    }

Upvotes: 0

Views: 1222

Answers (2)

JuanG
JuanG

Reputation: 41

If your authentication method is bearer, then you can just do [Authorize] and don't forget to use [ApiController] so .net knows it needs to verify each endpoint setup:

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Authorization;

namespace API
{
    [ApiController]
    [Authorize]
    [Route("api/Test")]
    public class TestController : ControllerBase
    {
        //...

       [HttpGet("Select")]
       public IActionResult Select()
       {
           try
           {
              return Ok(FirstService.Select());
           }
           catch (Exception ex)
           {
              return Conflict(ex);
           }
       }
//...

Upvotes: 0

John Glenn
John Glenn

Reputation: 1629

The issue that your BearerAuthenticationAttribute class extends the ActionFilterAttribute class but does not implement the IActionFilter interface. Your class must explicitly implement the IActionFilter interface for the OnActionExecuting method to fire.

Here is an example of the implementation from a Microsoft Hands On Lab:

public class CustomActionFilter : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        // TODO: Add your action filter's tasks here

        // Log Action Filter call
        using (MusicStoreEntities storeDb = new MusicStoreEntities())
        {
            ActionLog log = new ActionLog()
            {
                Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName,
                Action = string.Concat(filterContext.ActionDescriptor.ActionName, " (Logged By: Custom Action Filter)"),
                IP = filterContext.HttpContext.Request.UserHostAddress,
                DateTime = filterContext.HttpContext.Timestamp
            };
            storeDb.ActionLogs.Add(log);
            storeDb.SaveChanges();
            OnActionExecuting(filterContext);
        }
    }
}

Upvotes: 1

Related Questions