Spring Boot集成Active Directory认证配置求助
Hey there! Let's work through this Active Directory (AD) authentication issue with Spring Security together—your error gives us clear clues to fix this.
First, let's break down that error message:
LDAP: error code 49 - 80090308: LdapErr: DSID-0C090400, comment: AcceptSecurityContext error, data 52e
The 52e code specifically means invalid credentials in AD, but this usually stems from how we're constructing the user's Distinguished Name (DN) or using the wrong authentication flow, not necessarily the actual password being wrong.
Let's spot the issues in your current code:
- Mixing
userDnPatternsanduserSearchFilter: These two settings don't play well together.userDnPatternstries to build the user's DN directly, whileuserSearchFiltersearches for the user in the directory first. Since your AD usesCN(notuid) as the user identifier, we should stick with the search approach. - Hardcoded
userSearchFilter: Your filterCN=myCNis locked to a single user—this won't work for general authentication. It needs to be dynamic to match the username the user enters, likeCN={0}(the{0}gets replaced with the login username). - Unnecessary password compare setup: AD typically uses "bind authentication"—where we use the user's full DN and password to directly connect to the LDAP server. Comparing stored password attributes (your
passwordCompareblock) isn't needed here, as AD handles password validation internally during the bind.
Here's the corrected Kotlin code:
@Throws(Exception::class) override fun configure(auth: AuthenticationManagerBuilder) { auth .ldapAuthentication() // Dynamic filter to find the user by their CN matching the login username .userSearchFilter("CN={0}") // The base OU where we start searching for users .userSearchBase("OU=OU_1,OU=OU_2") // Optional: Set group search base only if you need group-based authorization .groupSearchBase("OU=OU_1,OU=OU_2") .contextSource() .url("ldap://{targeted AD IP:389}/DC=example,DC=com") // Optional: Add these lines if AD requires a service account to perform user searches // .userDn("CN=YourServiceAccount,OU=ServiceAccounts,DC=example,DC=com") // .password("yourServiceAccountPassword") }
A few extra tips:
- If all your users live in the exact same OU structure, you can skip the search and use
userDnPatternsdirectly (this is more efficient):.userDnPatterns("CN={0},OU=OU_1,OU=OU_2") - Make sure the login username matches the
CNvalue of the user in AD. For example, if the user's full DN isCN=Jane Smith,OU=OU_1,OU=OU_2,DC=example,DC=com, the login username should beJane Smith. - You don't need a
passwordEncoderhere—Spring Security will pass the raw password to AD for validation during the bind process.
内容的提问来源于stack exchange,提问作者Poorya Hosseini
相关产品推荐
相关产品推荐

