首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在没有GetUserId的IIdentity中伪装IIdentity和ControllerContext

如何在没有GetUserId的IIdentity中伪装IIdentity和ControllerContext
EN

Stack Overflow用户
提问于 2016-05-16 23:54:14
回答 1查看 1.7K关注 0票数 2

有一个简单的方法来模拟IIdentity.GetUserId和IIdentity.IsAuthenticated吗?

我用这种方式进行了测试,得到了一个NotSupportedException.

代码语言:javascript
复制
[Test]
public void CanGetUserIdFromIdentityTest()
{
    //Enviroment
    var mockIdentity = new Mock<IIdentity>();
    mockIdentity.Setup(x => x.Name).Returns("test@test.com");
    mockIdentity.Setup(x => x.IsAuthenticated).Returns(true);
    mockIdentity.Setup(x => x.GetUserId()).Returns("12345");

    var mockPrincipal = new Mock<IPrincipal>();
    mockPrincipal.Setup(x => x.Identity).Returns(mockIdentity.Object);
    mockPrincipal.Setup(x => x.IsInRole(It.IsAny<string>())).Returns(true);

    //Action
    Kernel.Rebind<IPrincipal>().ToConstant(mockPrincipal.Object);

    //Asserts
    var principal = Kernel.Get<IPrincipal>();
    Assert.IsNotNull(principal.Identity.GetUserId());
    Assert.IsTrue(principal.Identity.IsAuthenticated);
}

我也用GenericIdentity进行了测试。使用它,我可以模拟GetUserId(),但不能模拟GetUserId属性。

有人能帮我吗?

EN

回答 1

Stack Overflow用户

发布于 2016-05-17 00:33:04

您可以获得NotSupportedException,因为GetUserId是来自IdentityExtensions.GetUserId法的扩展方法,不属于模拟对象。没有必要模拟GetUserId

如果您查看GetUserId的源代码,您将看到它不适合您。

代码语言:javascript
复制
/// <summary>
///     Extensions making it easier to get the user name/user id claims off of an identity
/// </summary>
public static class IdentityExtensions
{
    /// <summary>
    ///     Return the user name using the UserNameClaimType
    /// </summary>
    /// <param name="identity"></param>
    /// <returns></returns>
    public static string GetUserName(this IIdentity identity)
    {
        if (identity == null)
        {
            throw new ArgumentNullException("identity");
        }
        var ci = identity as ClaimsIdentity;
        if (ci != null)
        {
            return ci.FindFirstValue(ClaimsIdentity.DefaultNameClaimType);
        }
        return null;
    }

    /// <summary>
    ///     Return the user id using the UserIdClaimType
    /// </summary>
    /// <param name="identity"></param>
    /// <returns></returns>
    public static string GetUserId(this IIdentity identity)
    {
        if (identity == null)
        {
            throw new ArgumentNullException("identity");
        }
        var ci = identity as ClaimsIdentity;
        if (ci != null)
        {
            return ci.FindFirstValue(ClaimTypes.NameIdentifier);
        }
        return null;
    }

    /// <summary>
    ///     Return the claim value for the first claim with the specified type if it exists, null otherwise
    /// </summary>
    /// <param name="identity"></param>
    /// <param name="claimType"></param>
    /// <returns></returns>
    public static string FindFirstValue(this ClaimsIdentity identity, string claimType)
    {
        if (identity == null)
        {
            throw new ArgumentNullException("identity");
        }
        var claim = identity.FindFirst(claimType);
        return claim != null ? claim.Value : null;
    }
}

它正在寻找一个带有ClaimTypes.NameIdentifierClaimTypes.NameIdentifier,这就是它为什么适用于GenericIdentity的原因。因此,这意味着您需要创建标识的存根。为了使IsAuthenticated工作,只需在构造函数中提供一个身份验证类型。空字符串就行了。

下面是更改的测试方法

代码语言:javascript
复制
[Test]
public void Should_GetUserId_From_Identity() {
    //Arrange
    var username = "test@test.com";
    var identity = new GenericIdentity(username, "");
    var nameIdentifierClaim = new Claim(ClaimTypes.NameIdentifier, username);
    identity.AddClaim(nameIdentifierClaim);

    var mockPrincipal = new Mock<IPrincipal>();
    mockPrincipal.Setup(x => x.Identity).Returns(identity);
    mockPrincipal.Setup(x => x.IsInRole(It.IsAny<string>())).Returns(true);

    Kernel.Rebind<IPrincipal>().ToConstant(mockPrincipal.Object);

    //Act
    var principal = Kernel.Get<IPrincipal>();

    //Asserts        
    Assert.AreEqual(username, principal.Identity.GetUserId());
    Assert.IsTrue(principal.Identity.IsAuthenticated);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37264994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档