简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM