我试图在我的spring boot app身份验证机制中使用Active Directory。我尝试使用spring 4安全性,但它没有用。
试图弄清楚出了什么问题,我在网上发现了很多错误,过了一会儿就用下面的代码解决了。
希望我的经历能帮助他人。
只需创建配置类
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.permitAll()
.logout()
.permitAll();
}
@Configuration
protected class AuthenticationConfiguration extends
GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
ActiveDirectoryLdapAuthenticationProvider provider=
new ActiveDirectoryLdapAuthenticationProvider(mySite.com
,ldap://10.1.112.115:389/);
provider.setAuthoritiesMapper(new MyMapper());
auth.authenticationProvider(provider);
}
}
}
映射器类用于设置角色
/**
* Maps groups defined in LDAP to roles for a specific user.
*/
public class MyMapper implements GrantedAuthoritiesMapper {
public MyMapper() {
}
public Collection<? extends GrantedAuthority> mapAuthorities( final Collection<? extends GrantedAuthority> authorities) {
Set<RolesEnum> roles = EnumSet.noneOf(RolesEnum.class);
for (GrantedAuthority authority : authorities) {
if (RolesEnum.ROLE_ADMIN.getAuthority().equals(authority.getAuthority())) {
roles.add(RolesEnum.ROLE_ADMIN);
}
}
return roles;
}
}
并持续使用简单的枚举
public enum RoleEnum implements GrantedAuthority {
// These roles are specified in the security application context and are
// mapped to LDAP roles by the AuthoritiesMapper
ROLE_ADMIN("LDAP_ADMIN");
private final String ldapGroupName;
/**
* @param text
*/
private RoleEnum(final String ldapGroupName) {
this.ldapGroupName = ldapGroupName;
}
public String getAuthority() {
return ldapGroupName;
}
}
在用户进行身份验证后,您可以使用他的角色 像RestController中那样的代码:
SecurityContext securityContext = (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
Authentication auth = securityContext.getAuthentication();
Collection<GrantedAuthority> granntedAuthorities = (Collection<GrantedAuthority>) auth.getAuthorities();
return granntedAuthorities.contains(RoleEnum);
}