- 导入相关的依赖:
org.springframework.security
spring-security-ldap
5.5.0
- 配置 Spring Security:
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userSearchBase("ou=people")
.userSearchFilter("(uid={0})")
.groupSearchBase("ou=groups")
.groupSearchFilter("(member={0})")
.contextSource()
.url("ldap://localhost:389/dc=springframework,dc=org")
.and()
.passwordCompare()
.passwordEncoder(new LdapShaPasswordEncoder())
.passwordAttribute("userPassword");
}
}
- 在 Active Directory 中配置用户和角色,例如:
dn: cn=TestUser,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: TestUser
sn: User
userPassword: {SHA}X03MO1qnZdYdgyfeuILPmQ==
uid: testuser
dn: cn=testrole,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfNames
cn: testrole
member: cn=TestUser,ou=people,dc=springframework,dc=org
- 在应用程序中使用 SecurityContextHolder 获取认证信息:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();