2017-12-18 158 views
1

我有一个项目根据LDAP Active Directory对用户进行身份验证,并根据成员资格限制对某些视图的访问。大部分工作都是在班上完成的/Models/AdAuthenticationService.cs目前为止一切正常;不过,我似乎无法能够显示在_Layout.cshtmlasp.net mvc如何显示GivenName和Surname而不是名称

我AdAuthenticationService类用户参数,如给定名称和姓有以下:

namespace MyFDM.Models { 
    public class AdAuthenticationService { 


    private ClaimsIdentity CreateIdentity(UserPrincipal userPrincipal) { 
     var identity = new ClaimsIdentity(MyAuthentication.ApplicationCookie, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); 
     identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Active Directory")); 
     identity.AddClaim(new Claim(ClaimTypes.Name, userPrincipal.SamAccountName)); 
     identity.AddClaim(new Claim(ClaimTypes.GivenName, userPrincipal.GivenName)); 
     identity.AddClaim(new Claim(ClaimTypes.Surname, userPrincipal.Surname)); 
     identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userPrincipal.SamAccountName)); 
     if (!String.IsNullOrEmpty(userPrincipal.EmailAddress)) { 
     identity.AddClaim(new Claim(ClaimTypes.Email, userPrincipal.EmailAddress)); 
     } 

而且我_LoginPartial.cshtml包含:

@if (Request.IsAuthenticated) 
 
{ 
 
       <a href="#" class="dropdown-toggle" data-toggle="dropdown">Hello @User.Identity.Name!<span class="caret"></span></a>

我可以指定任何标识的属性名称;例如:

identity.AddClaim(new Claim(ClaimTypes.Name, userPrincipal.DisplayName)); 

而这将显示正确的用户名而不是SamAccountName;但我真正需要做的是显示给定名称+姓,如:

@if (Request.IsAuthenticated) 
 
{ 
 
       <a href="#" class="dropdown-toggle" data-toggle="dropdown">Hello @User.Identity.GivenName + @User.Identity.Surname!<span class="caret"></span></a>

但如果我这样做,我得到以下错误: 错误CS1061“的IIdentity”不包含一个定义对于'GivenName'并且没有扩展方法'GivenName'可以被接受到'IIdentity'类型的第一个参数。

回答

0

我不知道这是否会有所帮助,但我这样做的方式是在返回UserPrincipal的助手类中创建一个方法(确保它不返回一个Principal或不是所有属性都会存在)。就像这样:

public class ADServices { 
     PrincipalContext prinContext = new PrincipalContext(ContextType.Domain, "ad"); 

     public UserPrincipal GetUser(string userName) { 
      UserPrincipal userPrin = UserPrincipal.FindByIdentity(prinContext, userName); 

      if (userPrin == null) { 
       throw new Exception("The username " + userName + " does not exist."); 
      } 

     return userPrin; 
    } 
} 

这提供了所有的属性,你可以找到详细的here到我的控制器,在这里我简单地把它应用到ViewBag.UserName

[HttpGet] 
    public async Task<ActionResult> Index() { 
     ADServices ads = new ADServices(); 
     var userPrin = ads.GetUser(User.Identity.Name); 
     ViewBag.UserName = userPrin.GivenName + " " + userPrin.Surname; 
     ...(other code omitted) 
     return View(model); 
    } 

,并使用了我的观点:

<p class="nav navbar-text navbar-right">Hello, @ViewBag.UserName!</p> 
相关问题