Zabavsky
Zabavsky

Reputation: 13640

IsAuthorized of the AuthorizeAttribute is always false in the unit test

I'm trying to test my custom AuthorizeAttribute, but the IsAuthorized method of the base class always returns false regardless of IsAuthenticated. Let me show you some code (some parts are omitted for brevity):

AuthorizeAttribute

public class UserAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        if (!base.IsAuthorized(actionContext)) // always returns false
            return false;

        //... not important user permission check

        return true;
    }
}

GetPrincipal method mocks IPrincipal

public static IPrincipal GetPrincipal()
{
    var user = new Mock<IPrincipal>();
    var identity = new Mock<IIdentity>();
    identity.Setup(x => x.Name).Returns("Superman");
    identity.Setup(p => p.IsAuthenticated).Returns(true);
    user.Setup(x => x.Identity).Returns(identity.Object);
    Thread.CurrentPrincipal = user.Object;

    return user.Object;
}

TestMethod

[TestMethod]
public void Test()
{
    HttpActionContext actionContext = ContextUtil.CreateActionContext();

    var attribute = new UserAuthorizeAttribute();
    IPrincipal user = Thread.CurrentPrincipal;

    // yep, this passes
    Assert.IsTrue(user.Identity.IsAuthenticated, "Superman is not authenticated");

    attribute.OnAuthorization(actionContext);
}

According to the source code of the attribute it should only check the Thread.CurrentPrincipal.Identity.IsAuthenticated as I'm not assigning any users or roles specifically. Any clue what am I missing here?

Upvotes: 2

Views: 4228

Answers (1)

JotaBe
JotaBe

Reputation: 39015

The principal is not taken from the current thread, but from the actionContext. So, what you must set is the principal in the request context of the action context:

actionContext.RequestContext.Principal = yourPrincipal;

Do this right after creating the action context, and before invoking the tested method.

Upvotes: 4

Related Questions