2017-12-18 160 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> 
相關問題