【问题标题】:identityserver3 custom usersevice not being called未调用 identityserver3 自定义用户服务
【发布时间】:2015-12-15 07:34:50
【问题描述】:

[编辑:添加用户服务代码]

当我的 IdentityServer 中的以下代码标记了 ADUserService 并且未标记 .UseInmemory(MemUser.TempUser) 代码时,一切正常。

当 InMemory 被标记并且两个 ADUserService 行没有被标记(如下面的代码)时,会显示相同的登录屏幕,但这次失败。调试时不显示日志,登录期间不输入 ADUserService,仅在调用启动代码期间。

我错过了什么吗?我做错了吗?

        // identityServer factory
        var factory = new IdentityServerServiceFactory()
        //            .UseInMemoryUsers(MemUser.TempUser) // Fix: Remove temp users!!
                    .UseInMemoryClients(CrbAuthClients.Get())
                    .UseInMemoryScopes(Scopes.AllSupportedScopes);

        var userService = new ADUserService();
        factory.UserService = new Registration<IUserService>(resolver => userService);



        // identityServer go!!
        var options = new IdentityServerOptions
        {
            SigningCertificate = Certificate.Load(),
            AuthenticationOptions = new AuthenticationOptions 
                    { 
                        SignInMessageThreshold = 1 // default is 5, prevents "Header Too Long" error
                    },
            Factory = factory
        };

        app.UseIdentityServer(options);

这可能是因为我使用了 Visual Studio 及其 IIS Express,其中的 https 未针对 IDServ3 服务器(在 Nancy 中)或我的 MVC 客户端进行验证?

可能是我需要添加 CORS 策略服务吗?我什么时候需要那个?我正在从单独的 MVC 项目和网站调用身份验证。

factory.CorsPolicyService = new Registration<ICorsPolicyService>(new DefaultCorsPolicyService { AllowAll = true });

这可能是我以前使用 inMem 用户的问题,现在有某种缓存仍在使用它们吗? (我检查了更改后停止工作的bob-secret,并在更改回内存用户时恢复工作)

----- 已编辑 -----

也许是因为我没有使用 ldapConnectionDelegate ? 我需要吗?

代码如下:

namespace Crb.Auth.AuthServer.Securing
{
    using System;
    using System.Configuration;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Threading.Tasks;
    using System.DirectoryServices;
    using System.Security.Claims;

    using System.DirectoryServices.AccountManagement;
    using IdentityServer3.Core;
    using IdentityServer3.Core.Services;
    using IdentityServer3.Core.Models;
    using IdentityServer3.Core.Extensions;
    using IdentityServer3.Core.Services.Default;

    using Serilog;

    // according to gist https://gist.github.com/rmbrunet/6c5c2ba2b8fb03fbc359
    // from rmbrunet on Stack Exchange here: https://github.com/IdentityServer/IdentityServer3/issues/1366

    // A slightly cleaner but less explicit approach (not used here) is in https://gist.github.com/tjrobinson/0ad6c790e90d7a385eb1
    // from rajarameshvarma on Stack Exchange here: https://github.com/IdentityServer/IdentityServer3/issues/995

    // Startup code is taken from the CustomUserService project in the IdentityServer3 Samples.

    public class ADUserService : UserServiceBase //UserServiceBase
    {
        static class ADAttributes
        {
            public static string SamAccountName = "samaccountname";
            public static string Mail = "mail";
            public static string UserGroup = "usergroup";
            public static string DisplayName = "displayname";
            public static string Department = "department";
            public static string StreetAddress = "streetAddress";
            public static string Phone = "telephoneNumber";
            public static string State = "st";
            public static string City = "l";
            public static string Zip = "postalCode";
            public static string Surname = "sn";
            public static string Givenname = "givenName";
        }

        const string ActiveDirectoryConnectionStringname = "CnnActiveDir";

        #region setup and construction
        //Func<string, string> _ldapConnectionDelegate; //Delegate that receives the domain and returns the LDAP connection string.

        // default ctor reads from connection string
        public ADUserService()//Func<string, string> ldapConnectionDelegate)
        {
            //_ldapConnectionDelegate = ldapConnectionDelegate;
            //Log.Debug("ADUserService called");
        }
        //.. region setup and construction
        #endregion

        #region authenticate with claims

        #region authenticate external - not supported
        public System.Threading.Tasks.Task<IdentityServer3.Core.Models.AuthenticateResult> AuthenticateExternalAsync(IdentityServer3.Core.Models.ExternalIdentity externalUser, IdentityServer3.Core.Models.SignInMessage message)
        {
            return Task.FromResult<AuthenticateResult>(null);
        }
        #endregion

        public Task<AuthenticateResult> AuthenticateLocalAsync(
            string userDomainAndName, // sometimes referred to as 'the subject'
            string password,
            SignInMessage message)
        {

            bool isUserValid = false;

            if (string.IsNullOrEmpty(userDomainAndName) 
                || userDomainAndName.IndexOf(@"\") < 1) // expected: some domain name given followed by a backslash
            {
                Log.Debug("Supplied username missing domain. Authentication denied.");
                return Task.FromResult<AuthenticateResult>(null); // Failed!! 
            }
            var split = userDomainAndName.ToLower().Split('\\'); //username assumed to be in the form domain\user
            string domain = split[0];
            string username = split[1];


            using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
            {
                isUserValid = pc.ValidateCredentials(username, password);
            }

            if (!isUserValid)
            {
                Log.Debug("Authentication attempt failed for {0}", userDomainAndName);
                return Task.FromResult<AuthenticateResult>(null);
            }

            return Task.FromResult<AuthenticateResult>(
                new AuthenticateResult(subject: username.ToLower(), name: username));
        }

        #region pre-authenticate async - not supported
        public System.Threading.Tasks.Task<IdentityServer3.Core.Models.AuthenticateResult> PreAuthenticateAsync(IdentityServer3.Core.Models.SignInMessage message)
        {
            return Task.FromResult<AuthenticateResult>(null);
        }
        #endregion
        //..region authenticate
        #endregion

        #region profile

        public System.Threading.Tasks.Task<IEnumerable<System.Security.Claims.Claim>> GetProfileDataAsync(
            System.Security.Claims.ClaimsPrincipal principal,
            IEnumerable<string> requestedClaimTypes = null)
        {

            List<System.Security.Claims.Claim> claims = new List<Claim>(); //x null;


            string subject = principal.GetSubjectId();
            if ( ! string.IsNullOrEmpty(subject) )
                claims.Add(new Claim(Constants.ClaimTypes.Subject, subject)); // notice: idsrv3 short name convention as opposed to claims with full type

            SearchResult result = findUser(subject);
            if (result != null &&
                result.Properties.Contains(ADAttributes.Mail) &&
                result.Properties.Contains(ADAttributes.DisplayName))
            {
                claims.Add(new Claim(ClaimTypes.Email, (String)result.Properties[ADAttributes.Mail][0]));
                claims.Add(new Claim(ClaimTypes.Name, (String)result.Properties[ADAttributes.DisplayName][0]));

                if (result.Properties.Contains(ADAttributes.Surname))
                    claims.Add(new Claim(ClaimTypes.Surname, (String)result.Properties[ADAttributes.Surname][0]));

                if (result.Properties.Contains(ADAttributes.Givenname))
                    claims.Add(new Claim(ClaimTypes.GivenName, (String)result.Properties[ADAttributes.Givenname][0]));

                //Is there an address?
                if (result.Properties.Contains(ADAttributes.State)
                    && result.Properties.Contains(ADAttributes.StreetAddress)
                    && result.Properties.Contains(ADAttributes.City)
                    && result.Properties.Contains(ADAttributes.Zip))
                {

                    string state = (String)result.Properties[ADAttributes.State][0];
                    string street = (String)result.Properties[ADAttributes.StreetAddress][0];
                    string city = (String)result.Properties[ADAttributes.City][0];
                    string zip = (String)result.Properties[ADAttributes.Zip][0];

                    string address = string.Format("{0}, {1}, {2} {3}", street, city, state, zip);
                    claims.Add(new Claim(ClaimTypes.StreetAddress, address));
                }

                // Get roles from AD user groups
                var prince = principal.Identity as UserPrincipal;
                var groups = prince.GetGroups();
                foreach (var group in groups)
                    claims.Add(new Claim(ClaimTypes.Role, "dpn:" + group.DisplayName+",dtn:"+group.DistinguishedName ));

                claims = claims.Where(x => requestedClaimTypes.Contains(x.Type)).ToList();
            }

            return Task.FromResult(claims.AsEnumerable());
        }
        //.. region profile
        #endregion

        #region sign-out

        public System.Threading.Tasks.Task SignOutAsync(System.Security.Claims.ClaimsPrincipal subject)
        {
            return Task.FromResult(0);
        }
        //..region sign-out
        #endregion

        #region internals

        SearchResult findUser(string subject)
        {
            string[] a = subject.Split('\\');

            string domain = a[0];
            string username = a[1];

            string node = ConfigurationManager.ConnectionStrings[ActiveDirectoryConnectionStringname].ConnectionString;
                            //x _ldapConnectionDelegate(domain);


            using (DirectoryEntry searchRoot = new DirectoryEntry(node))
            {
                using (DirectorySearcher search = new DirectorySearcher(searchRoot))
                {

                    search.Filter = string.Format("(&(objectClass=user)(objectCategory=person)(SAMAccountName={0}))", username);
                    //search.PropertiesToLoad.Add( Constants.ADAttributes.SamAccountName );
                    search.PropertiesToLoad.Add(ADAttributes.Mail);
                    search.PropertiesToLoad.Add(ADAttributes.UserGroup);
                    search.PropertiesToLoad.Add(ADAttributes.DisplayName);
                    search.PropertiesToLoad.Add(ADAttributes.Surname);
                    search.PropertiesToLoad.Add(ADAttributes.Givenname);
                    search.PropertiesToLoad.Add(ADAttributes.Department);
                    search.PropertiesToLoad.Add(ADAttributes.StreetAddress);
                    search.PropertiesToLoad.Add(ADAttributes.Phone);
                    search.PropertiesToLoad.Add(ADAttributes.State);
                    search.PropertiesToLoad.Add(ADAttributes.City);
                    search.PropertiesToLoad.Add(ADAttributes.Zip);

                    return search.FindOne();
                }
            }
        }

        public System.Threading.Tasks.Task<bool> IsActiveAsync(System.Security.Claims.ClaimsPrincipal principal)
        {
            string subject = principal.GetSubjectId(); // this should return the "distinguished name" (sub.maindomain/username)
            SearchResult result = findUser(subject);
            return Task.FromResult(result != null);
        }
        //.. region internals
        #endregion
    }
}

【问题讨论】:

  • 也许我做错的是我没有“上下文功能”。我将编辑问题并添加 userService 代码

标签: authentication active-directory identityserver3


【解决方案1】:

我看不出你所做的有什么明显的错误。你检查过日志吗?

我发现它们在实现 IdServer 时非常有用。您可以很容易地使用Serilog 将其写入控制台。

这里有一些示例代码;

public static void Configuration(IAppBuilder appBuilder)
{
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Debug()
        .WriteTo.Trace()
        .CreateLogger();

    //id server initialisation...
}

【讨论】:

  • 是的,我使用的是 serilog。调用构造函数后没有任何反应,构造函数本身被调用(并且什么都不做)然后在使用用户名和凭据在 IDSrv3 登录页面上按下登录后,它只是响应用户未授权
猜你喜欢
  • 1970-01-01
  • 2018-03-03
  • 2013-06-27
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
  • 2022-12-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多