UserPrincipal.EmployeeId не сохраняется после входа - PullRequest
0 голосов
/ 23 мая 2018

Я использую аутентификацию ActiveDirectory (от Microsoft.Owin), которая отлично подходит для того, что мне нужно, но я столкнулся с проблемой, когда EmployeeId не сохраняется, даже если я установил его во время процесса входа в систему.Я все еще пытаюсь изучить эту библиотеку, поэтому я немного запутался.Вот мой код:

AdAuthenticationService.cs

public class AdAuthenticationService
{
    public class AuthenticationResult
    {
        public string ErrorMessage { get; private set; }

        public bool IsSuccess => string.IsNullOrEmpty(ErrorMessage);

        public AuthenticationResult(string errorMessage = null)
        {
            ErrorMessage = errorMessage;
        }
    }

    private readonly IAuthenticationManager authenticationManager;

    public AdAuthenticationService(IAuthenticationManager authenticationManager)
    {
        this.authenticationManager = authenticationManager;
    }

    public AuthenticationResult SignIn(String username, String password)
    {
        // authenticates against your domain account
        ContextType authenticationType = ContextType.Domain;
        PrincipalContext principalContext = new PrincipalContext(authenticationType);
        bool isAuthenticated = false;
        UserPrincipal userPrincipal = null;
        try
        {
            var eacId = DatabaseOperations.Login(username.Trim(), password.Trim());
            if (eacId > 0)
            {
                principalContext.ValidateCredentials(username.Trim(), password.Trim(), ContextOptions.Negotiate);
                isAuthenticated = DatabaseOperations.Security(eacId) > 0;
                if (isAuthenticated)
                {
                    userPrincipal = new UserPrincipal(principalContext,
                        DatabaseOperations.GetFullNameByEacId(eacId), password, true);
                    userPrincipal.EmployeeId = eacId.ToString();
                }
            }
        }
        catch (Exception)
        {
            isAuthenticated = false;
            userPrincipal = null;
        }

        if (!isAuthenticated)
        {
            return new AuthenticationResult("Username or Password is not correct");
        }

        var identity = CreateIdentity(userPrincipal);

        authenticationManager.SignOut(ActiveDirectoryAuthentication.ApplicationCookie);
        authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);


        return new AuthenticationResult();
    }

    private ClaimsIdentity CreateIdentity(UserPrincipal userPrincipal)
    {
        var identity = new ClaimsIdentity(ActiveDirectoryAuthentication.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.NameIdentifier, userPrincipal.SamAccountName));

        return identity;
    }
}

В методе SignIn вы можете установить eacId в userPrincipal.EmployeeId, однако при попыткечтобы получить к нему доступ из любого другого места в моем проекте, он возвращает ноль.

Я предполагаю, что из-за метода CreateIdentity мне следует добавить новое утверждение к объекту идентификации?Но у объекта нет ничего для EmployeeId, что мне и нужно.

1 Ответ

0 голосов
/ 23 мая 2018

Я не видел, чтобы вы добавили EmployeeId в качестве претензии.

private ClaimsIdentity CreateIdentity(UserPrincipal userPrincipal)
{
   var identity = new ClaimsIdentity(ActiveDirectoryAuthentication.ApplicationCookie, 
        ClaimsIdentity.DefaultNameClaimType, 
        ClaimsIdentity.DefaultRoleClaimType);
   ...
   identity.AddClaim(new Claim("EmployeeId", userPrincipal.EmployeeId));

   return identity;
}
...