根据百里香的安全性page,我可以得到如下记录的用户名和角色:
Logged user: <span sec:authentication="name">Bob</span>
Roles: <span sec:authentication="principal.authorities">[ROLE_USER, ROLE_ADMIN]</span>
我有一个Web应用程序,其中使用ActiveDirectoryLdapAuthenticationProvider
通过活动目录进行身份验证,如下所示:
@Bean
@Override
public AuthenticationManager authenticationManager() {
return new ProviderManager(Arrays.asList(activeDirectoryLdapAuthenticationProvider()));
}
@Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(adDomain,
adUrl);
provider.setConvertSubErrorCodesToExceptions(true);
provider.setUseAuthenticationRequestCredentials(true);
return provider;
}
然后,在用户登录后,我在所有带有以上sec:authentication="name"
thymeleaf标记的页面中使用标题页来显示用户名,但是我想查看是否有一种方法来显示全名代替。
解决方案提示here对我不起作用:
我正在使用:thymeleaf-extras-springsecurity5
并使用:<span th:text ="${#authentication.getPrincipal().getUser().getFirstName()}"></span>
给我:Method getUser() cannot be found on type org.springframework.security.ldap.userdetails.LdapUserDetailsImpl
该信息似乎来自:org.springframework.security.ldap.userdetails.LdapUserDetailsImpl
,只有几个选项(例如用户名),但不是AD可以拥有的其余信息。
答案 0 :(得分:1)
这是我解决问题的方式:
第一
我向提供者添加了UserDetailsContextMapper
和org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper
,如下所示:
@Bean
public AuthenticationProvider activeDirectoryLdapAuthenticationProvider() {
ActiveDirectoryLdapAuthenticationProvider provider = new ActiveDirectoryLdapAuthenticationProvider(adDomain, adUrl);
provider.setConvertSubErrorCodesToExceptions(true);
provider.setUseAuthenticationRequestCredentials(true);
provider.setUserDetailsContextMapper(userDetailsContextMapper()); <---
return provider;
}
@Bean
public UserDetailsContextMapper userDetailsContextMapper() {
return new LdapUserDetailsMapper() {
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
InetOrgPersonContextMapper personContextMapper = new InetOrgPersonContextMapper();
return personContextMapper.mapUserFromContext(ctx, username, authorities);
}
};
}
第二
然后在我的标题页中添加:
<span th:text ="${#authentication.getPrincipal().getDisplayName()}"></span>
显示全名。
使用这种方法,您还可以显示所有其他与AD相关的字段,例如:
<span th:text ="${#authentication.getPrincipal().getMail()}"></span>
<span th:text ="${#authentication.getPrincipal().getTelephoneNumber()}"></span>
<span th:text ="${#authentication.getPrincipal().getRoomNumber()}"></span>