2015-12-15 66 views
2

[编辑:增加了UserService代码]identityserver3定制usersevice不会被调用

当我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快递在HTTPS是不是无论是IDServ3服务器(南锡)或我的MVC客户端验证?

难道我需要添加CORS策略服务吗?我什么时候需要这个?我从单独的MVC项目和网站调用身份验证。

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

难道是因为我以前使用inMem用户的问题,现在有某种缓存的地方还在使用? (我查了鲍勃 - 秘密制止了变更后的工作,并改回时对内存中的用户返回工作)

----- -----编辑

也许是因为对我没有使用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 
    } 
} 
+0

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

回答

0

我看不出什么明显的毛病,你在做什么。你检查过日志吗?

我发现它们在实现IdServer时非常有用。你可以很容易地用Serilog写出来。

下面是一些示例代码;

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

    //id server initialisation... 
} 
+0

是的,我使用了serilog。在调用构造函数之后没有任何反应,构造函数本身被调用(并且什么都不做)然后在用ID和用户名登录IDSrv3登录页面之后,它只是回应用户没有被授权 – pashute