获取使用Spring Securitu通过Active Directory登录的用户的电子邮件地址

JDi*_*rro 5 java spring-mvc active-directory spring-security

我正在开发基于Spring MVC的Web应用程序,该应用程序使用Spring Security允​​许用户使用其Active Directory凭据登录.我想在用户登录后获取用户的电子邮件地址.我已经登录了工作,现在我正在试图找出如何获取用户的电子邮件.看起来我应该从一个InetOrgPerson对象那里得到它.我已经尝试InetOrgPersonContextMapper在xml配置中指定一个如下:

<bean id="ldapActiveDirectoryAuthProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
    <constructor-arg name="domain" value="foo.bar" />
    <constructor-arg name="url" value="ldap://foo.bar" />
    <property name="useAuthenticationRequestCredentials" value="true" />
    <property name="convertSubErrorCodesToExceptions" value="true" />
    <property name="userDetailsContextMapper">
        <bean class="org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper" />
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

我试图在控制器中收到这样的电子邮件:

@RequestMapping(value = "/startProcess.html", method = RequestMethod.POST)
public ModelAndView startProcess(@ModelAttribute Token token, Principal principal)
{
    ModelAndView mav = new ModelAndView();

    String user = principal.getName();
    String email = ((InetOrgPerson)principal).getMail();

    logger.info("Got email \"" + email + "\" for user \"" + user + "\"");

    ...
}
Run Code Online (Sandbox Code Playgroud)

这给了我一个类强制转换异常,说它不能转换UsernamePasswordAuthenticationToken为a InetOrgPerson.我决定尝试Principal手动获取对象,而不是让Spring注入它:

@RequestMapping(value = "/startProcess.html", method = RequestMethod.POST)
public ModelAndView startProcess(@ModelAttribute Token token, Principal principal)
{
    ModelAndView mav = new ModelAndView();

    String user = principal.getName();

    Object p = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String email = ((InetOrgPerson)p).getMail();

    logger.info("Got email \"" + email + "\" for user \"" + user + "\"");

    ...
}
Run Code Online (Sandbox Code Playgroud)

这告诉我它无法投射LdapUserDetailsImplInetOrgPerson.不LdapUserDetailsImpl应该是InetOrgPerson因为我正在使用InetOrgPersonContextMapper

JDi*_*rro 1

我忽略了这样一个事实:我正在使用自定义AuthenticationSuccessHandler并在用户登录后Authentication用 a覆盖。UsernamePasswordAuthenticationToken

我将 留InetOrgPersonContextMapper在 上ActiveDirectoryLdapAuthenticationProvider,并在我的AuthenticationSuccessHandler中将 投射PrincipalInetOrgPerson并将其存储为PrincipalUsernamePasswordAuthenticationToken。之后,我可以成功地将 转换为控制器中的Principalan并调用.InetOrgPersongetMail()