【问题标题】:How to mock claims in C#?如何在 C# 中模拟声明?
【发布时间】:2021-03-03 15:19:19
【问题描述】:

我目前正在开发一个使用 System.Security.ClaimsPrincipal 的 API。

我的API方法代码如下:

 var identityClaims = User.Claims; // User is part of System.security.claimsPrincipal
 var firstname = identityClaims .FirstOrDefault(c => c.Type == "firstname").Value;
 var lastname = identityClaims .FirstOrDefault(c => c.Type == "lastname").Value;

我想创建一个单元测试,我可以在其中模拟 FirstNameLastName 的值。

我在网上看到过下面的示例,但它似乎只设置了 1 个声明值 - John Doe,而我需要设置 FirstNameLastName

var claims = new List<Claim>() 
{ 
    new Claim(ClaimTypes.Name, "username"),
    new Claim(ClaimTypes.NameIdentifier, "userId"),
    new Claim("name", "John Doe"),
};
var identity = new ClaimsIdentity(claims, "TestAuthType");
var claimsPrincipal = new ClaimsPrincipal(identity);

如何根据上面的例子模拟名字和姓氏?

ClaimTypes.xxxx 没有为我提供 FirstName、LastName 的任何选项。

【问题讨论】:

    标签: c# api claims


    【解决方案1】:

    您可以为此设置声明类型GivenNameSurname

    new Claim(ClaimTypes.Email, user.Email), // Email
    // Dotnet uses this as username but its used differently. Facebook uses this as full name.
    new Claim(ClaimTypes.Name, user.FullName), // Full Name
    new Claim(ClaimTypes.GivenName, user.FirstName), // First Name
    new Claim(ClaimTypes.Surname, user.LastName), // Last Name
    new Claim(ClaimTypes.NameIdentifier, user.UserUniqueIdentifier.ToString()) // User Id or User Name
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-14
      • 2021-09-14
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      相关资源
      最近更新 更多