Dea*_*ell 6 java spring ldap spring-security spring-security-ldap
总之,用户正在经过身份验证,但我似乎确实已经登录到用户帐户。
我目前正在一个项目上实施 LDAP 身份验证。看来,身份验证部分正在工作,因为我的应用程序确实接受了正确的凭据。我遇到的问题是我似乎无法在 jsp 视图中访问“principal”。(在切换到 LDAP 之前我能够访问所有这些)。运行跟踪时,我的 CustomUserDetails 服务正在查询并提取正确的帐户信息。任何帮助表示赞赏
这将显示正确的用户名:
<sec:authorize access="isAuthenticated()">
<h2><sec:authentication property="name"/></h2>
</sec:authorize>
Run Code Online (Sandbox Code Playgroud)
这不起作用(它在 LDAP 之前确实有效)
<sec:authorize access="isAuthenticated()">
<h2><sec:authentication property="principal.firstName"/></h2>
</sec:authorize>
Run Code Online (Sandbox Code Playgroud)
相关代码SecurityConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.ldap.authentication.UserDetailsServiceLdapAuthoritiesPopulator;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Autowired
private CustomUserDetailsService userDetailsService;
@Bean
public CustomSaltSource customSaltSource(){ return new CustomSaltSource();}
@Bean
public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
return new AuthenticationSuccessHandler();
}
@Autowired
void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication().contextSource()
.url("ldap://bar.foo.com")
.port(####)
.and()
.userDnPatterns("cn={0},cn=users,dc=ms,dc=ds,dc=foo,dc=com")
.ldapAuthoritiesPopulator(new UserDetailsServiceLdapAuthoritiesPopulator(userDetailsService));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/skins/**", "/css/**", "/**/laggingComponents", "/assets/**").permitAll().and()
.formLogin().loginPage("/login").permitAll().defaultSuccessUrl("/", true).successHandler(myAuthenticationSuccessHandler())
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).deleteCookies("JSESSIONID").permitAll()
.and().authorizeRequests().antMatchers("/api/**").anonymous()
.and().authorizeRequests().anyRequest().authenticated().and().rememberMe().key("KEY").userDetailsService(userDetailsService);
}
@Override
public void configure(WebSecurity web) throws Exception {
DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
handler.setPermissionEvaluator(new PermissionEvaluator());
web.expressionHandler(handler);
web.ignoring().antMatchers( "/skins/**", "/css/**", "/api/**", "/assets/**", "/health"); //"/**/test/**"
}
}
Run Code Online (Sandbox Code Playgroud)
CustomUserDetailsService.java
import org.hibernate.Session;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service
public class CustomUserDetailsService implements UserDetailsService{
@Override
public CustomUserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
Session session = DBFactory.factory.openSession();
User user = (User) session.createQuery("from User where userName =:userName")
.setParameter("userName", username).uniqueResult();
if(user == null){
throw new UsernameNotFoundException("User Not Found");
}
//Needed to initialize permissions
Set<Role> roles = user.getRoles();
int i = roles.size();
for(Role role: roles){
int j = role.getPermissions().size();
}
CustomUserDetails userDetails = new CustomUserDetails(user);
session.close();
return userDetails;
}
}
Run Code Online (Sandbox Code Playgroud)
Yer*_*nov 10
如果我没记错的话,您切换到 Ldap 授权,设置 url 和 DN 模式,但仍然提供 userDetailsService 在数据库中搜索用户。您需要通过实现接口并创建自定义接口来设置UserDetailsContextMapper 。这会将数据从 ldap 目录上下文映射到您的自定义UserDetails并通过mapUserFromContext方法返回它。
这是一个示例CustomUserDetailsContextMapper:
public class CustomUserDetailsContextMapper implements UserDetailsContextMapper {
private LdapUser ldapUser = null;
private String commonName;
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
Attributes attributes = ctx.getAttributes();
UserDetails ldapUserDetails = (UserDetails) super.mapUserFromContext(ctx,username,authorities);
try {
commonName = attributes.get("cn").get().toString();
} catch (NamingException e) {
e.printStackTrace();
}
ldapUser = new LdapUser(ldapUserDetails);
ldapUser.setCommonName(commonName);
return ldapUser;
}
@Override
public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
}
}
Run Code Online (Sandbox Code Playgroud)
我的自定义LdapUser:
public class LdapUser implements UserDetails
{
private String commonName;
private UserDetails ldapUserDetails;
public LdapUser(LdapUserDetails ldapUserDetails) {
this.ldapUserDetails = ldapUserDetails;
}
@Override
public String getDn() {
return ldapUserDetails.getDn();
}
@Override
public void eraseCredentials() {
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return ldapUserDetails.getAuthorities();
}
@Override
public String getPassword() {
return ldapUserDetails.getPassword();
}
@Override
public String getUsername() {
return ldapUserDetails.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return ldapUserDetails.isAccountNonExpired();
}
@Override
public boolean isAccountNonLocked() {
return ldapUserDetails.isAccountNonLocked();
}
@Override
public boolean isCredentialsNonExpired() {
return ldapUserDetails.isCredentialsNonExpired();
}
@Override
public boolean isEnabled() {
return ldapUserDetails.isEnabled();
}
}
Run Code Online (Sandbox Code Playgroud)
然后在 auth 配置中设置 CustomUserDetailsContextMapper。这是您从authentication.getPrincipal()获取用户的方式。我希望我正确理解你的问题并回答。
归档时间: |
|
查看次数: |
9000 次 |
最近记录: |