0

I'm using Entity framework with JWT token generator in my web API. Every controller is [Authorize] in order to prevent not authorized api calls. So, when the client calls the api, it sends an header containing the token in order to be evaluated. Is there a possible way to read this token? It contains an information regarding a company user value and it is necessary in order to define the correct database.

[Authorize]
[ApiController]
public class MyClass: ControllerBase
{
    private readonly IMessageRepository dB;

   
    public MyClassController(IMessageRepository messageRepository)
    {
        this.dB = messageRepository;
    // something to retrieve header here.
      
    }

    /// <summary>
    /// Return the list of X contained in the DB
    /// </summary>
   
    [HttpGet(ApiRoutes.MyRoute)]
    public List<Object> Get()
    {
        var x = dB.Get();
        return x;
    }

I don't know if it's possible but Header should be retrieved in constructor and not in Api method.

3
  • 1
    "Header should be retrieved in constructor"...this makes no sense. The constructor doesn't process HTTP requests, the methods do. It is instantiated before any incoming request is processed. What's wrong with receiving it in the method? Or if you need something you can re-use across lots of methods, consider an action filter. Commented Dec 9, 2020 at 17:06
  • Ok perfect thanks!!! Could you provide an example in order to get it in a method? Thanks so much ! Commented Dec 9, 2020 at 17:13
  • There are plenty of previous questions already about how to retrieve a header value, e.g. stackoverflow.com/questions/27971340/… (and more) Commented Dec 9, 2020 at 17:15

1 Answer 1

1

What I understand from your question is that you said the Authorize attribute hits before the action method hits and it automatically decides that this call needs to come inside to the action method or not and you want to capture that call.

So my friend there are couples of Action Filter in Mvc which call before and after action method and "Authorize filter" always run before your action method once I run into this issue and on that time I used Custom attribute for capturing the stuff.

This class is inherited from "AuthorizeAttribute" and also [Authorize] derived from "AuthorizationFilterAttribute" abstract class so we override in a sense here.

you can more custom it in your usage way

Maybe this will help you out!

 public class CustomAuthorize : AuthorizeAttribute
    {
        public string Permissionname { get; set; }
         public CustomAuthorize (string PermissionName)
        {
            Permissionname = PermissionName;
        }
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            ClaimsIdentity claimsIdentity = HttpContext.Current.User.Identity as ClaimsIdentity;
            var _roles = claimsIdentity.FindAll(ClaimTypes.Role).ToList();
            bool isAuthorized = false;
            if (Permissionname!= "" && Permissionname != "AuthorizeOnly")
            {
                foreach (var item in _roles)
                {
                    if (item != null && item.Value != null && item.Value.ToLower() == Permissionname.ToLower())
                    {
                        isAuthorized = base.IsAuthorized(actionContext);
                    }
                }
            }
            else
            {
                isAuthorized = base.IsAuthorized(actionContext);
            }
            return isAuthorized;
        }
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
                //Setting error message and status Code 403 for unauthorized user
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(new { Message = "Authorization failed or user don't have permission!" })),
                    StatusCode = HttpStatusCode.Forbidden
                };

        }
    }

You can call like that on your action method

CustomAuthorize("CanViewLeads")]
Public HttpResponseMessage ActionMethodXYZ()
{
}

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.