I have a project that authenticates a user against LDAP Active Directory and restrict access to certain views based on Membership. Most of the work is done in a class /Models/AdAuthenticationService.cs
Everything works fine so far; however, I can't seem to be able to show user parameters like GivenName and Surname in the _Layout.cshtml
My AdAuthenticationService class has the following:
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));
}
And my _LoginPartial.cshtml contains:
@if (Request.IsAuthenticated)
{
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Hello @User.Identity.Name!<span class="caret"></span></a>
I can assign any of the Identity attributes to Name; for example:
identity.AddClaim(new Claim(ClaimTypes.Name, userPrincipal.DisplayName));
And this would display the correct user name instead of the SamAccountName; But what I really need to do is show GivenName + Surname like:
@if (Request.IsAuthenticated)
{
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Hello @User.Identity.GivenName + @User.Identity.Surname!<span class="caret"></span></a>
But if I do this, I get the following Error: Error CS1061 'IIdentity' does not contain a definition for 'GivenName' and no extension method 'GivenName' accepting a first argument of type 'IIdentity' could be found.
答案 0 :(得分: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>