Позволяет разорвать этот вверх в 2-х частей. Прежде всего, это будет ваша конфигурация xml безопасности весны, а вторая часть будет переопределять UserContextMapper, который обеспечивает весенняя безопасность.
Ваша конфигурация XML безопасности будет
<bean id="adAuthenticationProvider"
class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
<constructor-arg value="my.domain.com" />
<constructor-arg value="ldap://<adhostserver>:<port>/" />
<property name="convertSubErrorCodesToExceptions" value="true" />
<property name="userDetailsContextMapper" ref="myUserDetailsContextMapper" />
</bean>
<bean id="myUserDetailsContextMapper" class="com.mycompany.sme.workflow.controller.MyDbAuthorizationFetcher">
<property name="dataSource" ref="dataSource" />
MyDbAuthorizationFetcher класс, где бы реализации UserContextMapper класс, чтобы принести власти из БД
public class MyDbAuthorizationFetcher implements UserDetailsContextMapper {
private JdbcTemplate jdbcTemplate;
@Autowired
private DataSource dataSource;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
// populating roles assigned to the user from AUTHORITIES table in DB
private List<SimpleGrantedAuthority> loadRolesFromDatabase(String username) {
DbRole role = new DbRole();
String sql = "select * from user where user_id = ?";
jdbcTemplate = new JdbcTemplate(getDataSource());
role = jdbcTemplate.queryForObject(sql, new Object[] { username }, new DbRoleMapper());
try {
dataSource.getConnection().setAutoCommit(true);
} catch (SQLException e) {
}
List<SimpleGrantedAuthority> authoritiess = new ArrayList<SimpleGrantedAuthority>();
SimpleGrantedAuthority auth = new SimpleGrantedAuthority(String.valueOf(role.getRoleId()));
authoritiess.add(auth);
return authoritiess;
}
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx,
String username, Collection<? extends GrantedAuthority> authorities) {
List<SimpleGrantedAuthority> allAuthorities = new ArrayList<SimpleGrantedAuthority>();
for (GrantedAuthority auth : authorities) {
if (auth != null && !auth.getAuthority().isEmpty()) {
allAuthorities.add((SimpleGrantedAuthority) auth);
}
}
// add additional roles from the database table
allAuthorities.addAll(loadRolesFromDatabase(username));
return new User(username, "", true, true, true, true, allAuthorities);
}
@Override
public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
// TODO Auto-generated method stub
}
}
Спасибо большое. Как мне это сделать? Я довольно новичок в этой технике, и я не смог найти какой-либо пример, который использует ActiveDirectoryLdapAuthenticationProvider с пользовательскими loadUserAuthorities. –
Просто расширьте класс, позвоните в свою базу данных, чтобы получить роли, и верните их как «Список» в соответствии с методом подпись. Вы можете использовать класс SimpleGrantedAuthority для обертывания отдельных ролей. –
Я пытался расширить его, но я получаю ошибку: не могу подклассифицировать последний класс ActiveDirectoryLdapAuthenticationProvider –