Custom Authorization filter, no IPrincipal RRS feed

  • Question

  • User-332001849 posted

    I'm trying to write my own authorization attribute for WebAPI which relies on the IPrincipal being populated,  code is as follows...

    protected virtual bool AuthorizeCore(HttpActionContext actionContext)
        var request = actionContext.ControllerContext.Request;
    // NB Without the Thread.CurrentPrincipal we are always null     var principal = request.GetUserPrincipal() ?? Thread.CurrentPrincipal;    if (principal == null || principal.Identity.IsAuthenticated)     {         return false;     }

    This is very similar to the code base for the default WebAPI AuthorizeAttribute but they get away without calling Thread.CurrentPrincipal.

    Inside the ApiController, User is correctly populated (as is Thread.CurrentPrincipal), but why does request.GetUserPrincipal() not have a value?



    Wednesday, May 13, 2015 9:11 AM


  • User1644755831 posted

    Hello paulhatcher,

    Please see this article  : Authentication and Authorization in ASP.NET Web API

    As per the article  If your application performs any custom authentication logic, you must set the principal on two places:

    1. Thread.CurrentPrincipal. This property is the standard way to set the thread's principal in .NET.

    2. HttpContext.Current.User. This property is specific to ASP.NET.

    The following code shows how to set the principal:

    private void SetPrincipal(IPrincipal principal)
        Thread.CurrentPrincipal = principal;
        if (HttpContext.Current != null)
            HttpContext.Current.User = principal;

    Same thing has been described here in this article about implementing Custom Authorization Filters

    WebAPI Security – Custom Authorization Filters

    in the article he passes the authentication values from the client

    client.DefaultRequestHeaders.Authorization =  new AuthenticationHeaderValue("Basic",Convert.ToBase64String(encoder.GetBytes(string.Format("{0}:{1}","firstusername", "firstpassword"))));

    and on the server side he sets the Thread Principal

    Hope this helps.

    With Regards,

    Krunal Parekh

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, May 14, 2015 4:01 AM