springcloud 继承ldap
时间: 2023-07-06 22:23:44 浏览: 162
Spring Boot 连接LDAP的方法
Spring Cloud 中可以使用 Spring Security 来实现 LDAP 认证,具体步骤如下:
1. 配置 pom.xml,引入 Spring Security 和 Spring LDAP 相关依赖:
```xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>${spring-ldap.version}</version>
</dependency>
```
2. 配置 application.yml,设置 LDAP 连接信息:
```yaml
spring:
ldap:
urls: ldap://localhost:389
base: dc=my-domain,dc=com
username: cn=Manager,dc=my-domain,dc=com
password: password
```
3. 配置 WebSecurityConfigurerAdapter,实现 LDAP 认证:
```java
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private Environment env;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout();
http.csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.userSearchBase(env.getProperty("spring.ldap.user-search-base"))
.userSearchFilter(env.getProperty("spring.ldap.user-search-filter"))
.groupSearchBase(env.getProperty("spring.ldap.group-search-base"))
.groupSearchFilter(env.getProperty("spring.ldap.group-search-filter"))
.contextSource()
.url(env.getProperty("spring.ldap.urls"))
.managerDn(env.getProperty("spring.ldap.username"))
.managerPassword(env.getProperty("spring.ldap.password"));
}
}
```
这样就可以通过 LDAP 认证来控制访问权限了。在这个例子中,请求 "/admin/**" 的用户需要拥有 ADMIN 角色,请求 "/user/**" 的用户需要拥有 USER 角色,其他请求需要认证通过即可访问。
阅读全文