Retrieve user Token contained in Client Header in Web API C#

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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()
{
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x