Thymeleaf-获取已验证用户的全名 [英] Thymeleaf - Getting full name of authenticated user

查看:34
本文介绍了Thymeleaf-获取已验证用户的全名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据胸腺叶安全性page我可以获取登录的用户名和角色如下:

Logged user: <span sec:authentication="name">Bob</span>
Roles: <span sec:authentication="principal.authorities">[ROLE_USER, ROLE_ADMIN]</span>

我有一个Web应用程序,其中使用ActiveDirectoryLdapAuthenticationProvider通过Active Directory进行身份验证,如下所示:

@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"胸腺叶标记来显示用户名,但是我想看看是否有办法显示全名。

建议的解决方案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并且只有几个选项,如用户名,但不包括广告可以拥有的信息的睡觉。

推荐答案

我是这样解决问题的:

第一个

我向提供程序添加了UserDetailsContextMapperorg.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>

这篇关于Thymeleaf-获取已验证用户的全名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆