如何使用 LDAP 和基于角色的数据库授予权限来实现 Spring Security? [英] How to implement Spring Security with LDAP and Role based granted authorities from database?
问题描述
我在 Spring MVC Thymeleaf 项目中工作,其中具有数据库和基于角色的授权权限的 LDAP 安全性是最终用户的必备要求.
I am working in a Spring MVC Thymeleaf project where LDAP security with Database and Role-based granted authorities is a must-have requirement from the end-user.
我需要什么
- 主要身份验证应由 LDAP 执行
- 必须在数据库中配置用户角色和授予权限以及 LDAP 用户名
将在网页中用作hasAuthority("permission_x")"
example:
LDAP user: nahid@test.com
Role: Admin
Granted Authorities for "Admin" role: permission_x,permission_y etc
- LDAP认证后,系统会检查数据库中的用户是否作为白名单用户存在
- 白名单检查后,为用户加载角色和权限,对加载的权限(非角色)进行授权
Spring Security with LDAP and Database roles, which is a bit outdated
- 我需要用 LDAP 用户名存储 LDAP 密码吗?如果是,是否安全?
- 上述场景是否存在任何示例?
- 细粒度的授予权限是否适用于 LDAP 用户?
- Do I need to store LDAP Password with LDAP user Name? If yes, is it safe?
- Is there any example that exists for the above scenario?
- Will fine-grained granted authorities work for LDAP users?
- 无需在数据库中存储密码.
- 不完全是
- 是的,细粒度的授予权限非常适合 LDAP 用户
我在这里找到了:
https://spring.io/guides/gs/authenticating-ldap/ 仅显示 LDAP 身份验证.
现在我的问题是:
LDAP 身份验证和基于 jdbc 的授权如何协同工作?有人可以帮忙吗?
提前致谢
推荐答案
既然我找到了解决方案,我在这里分享我自己的答案.希望对其他人有所帮助:
我的答案是:
我是如何解决我的问题的:
第 1 步:
诀窍是使用 UserDetailsContextMapper 和常规 UserDetailsService 提供的 UserDetails.
Step 1:
示例:
example:
LDAP 身份验证成功后,它会尝试将有效的注册用户加载到具有所有授予权限的上下文中.
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDetailsContextMapper(userDetailsContextMapper())
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.url("ldap://localhost:8389/dc=springframework,dc=org")
.and()
.passwordCompare()
.passwordEncoder(new BCryptPasswordEncoder())
.passwordAttribute("userPassword");
}
@Bean
public UserDetailsContextMapper userDetailsContextMapper() {
return new LdapUserDetailsMapper() {
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
UserDetails details= userDetailsService.loadUserByUsername(username+"@test.com");
return details;
}
};
}
第 2 步
hasAuthority 对我不起作用.我用过类似下面的东西:
Step 2
hasAuthority didn't work for me. I have used something like below:
为了快速检查,您可以使用以下:
For a quick check, you can use below:
<span sec:authentication="principal.authorities"></span>
我希望有一天它会对某人有所帮助.
I hope it will help somebody someday.
编码愉快!
用于 LDAP over SSL 和 Spring Boot
这篇关于如何使用 LDAP 和基于角色的数据库授予权限来实现 Spring Security?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!