Tigran Petrosyan
Tigran Petrosyan

Reputation: 127

AuthorizeAttribute is not working in .net 5 web api

I am trying to implement custom authorization using System.Web.Http.AuthorizeAttribute, but It is not working. I have the following controller:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using WebApplication2.Helpers;

namespace WebApplication2.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : Controller
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        [CustomAuthorize]

        public IEnumerable<WeatherForecast> Get()
        {
            if (User.Identity.IsAuthenticated)
            {

            }
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

And I created custom authorize attribute:

using System;
using System.Web.Http.Controllers;

namespace WebApplication2.Helpers
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class CustomAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw new Exception();
            }
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            bool isAuthroized = base.IsAuthorized(actionContext);

            return isAuthroized;
        }
    }
}

When calling Get weather forecast neither of OnAuthorization and IsAuthorized methods called. Can you please explain what is the problem here ?

Upvotes: 0

Views: 2534

Answers (1)

Alexander
Alexander

Reputation: 9642

You are using AuthorizeAttribute from System.Web.Http namespace which is not used by ASP.NET Core. Implement IAuthorizationFilter interface instead

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomAuthorizeAttribute : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        //...
    }
}

Upvotes: 2

Related Questions