我正在开发一个基于 Spring MVC 的 Web 应用程序,它使用 Spring Security 来允许用户使用他们的 Active Directory 凭据登录。我想在用户登录后获取他们的电子邮件地址。我的登录工作正常,现在我想弄清楚如何获取用户的电子邮件。看起来我应该从 InetOrgPerson
对象中获取它。我试过在 xml 配置中指定一个 InetOrgPersonContextMapper
:
<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>
我正在尝试像这样在 Controller 中获取电子邮件:
@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 + "\"");
...
}
这给了我一个类转换异常,说它不能将 UsernamePasswordAuthenticationToken
转换为 InetOrgPerson
。我决定尝试手动获取 Principal
对象,而不是让 Spring 注入(inject)它:
@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 + "\"");
...
}
这告诉我它不能将 LdapUserDetailsImpl
转换为 InetOrgPerson
。 LdapUserDetailsImpl
不应该是 InetOrgPerson
因为我使用的是 InetOrgPersonContextMapper
吗?
最佳答案
首先您需要将映射器更改为 org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper
<beans:bean id="inetOrgPersonContextMapper" class="org.springframework.security.ldap.userdetails.InetOrgPersonContextMapper">
</beans:bean>
然后在您的身份验证提供程序中使用它
<beans:bean id="adAuthenticationProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
<beans:constructor-arg value="mydomain.com.local" />
<beans:constructor-arg value="ldap://servername/" />
<beans:property name="userDetailsContextMapper" ref="inetOrgPersonContextMapper" />
</beans:bean>
然后你就可以将你的委托(delegate)人转换为 InetOrgPerson
InetOrgPerson userDetails = (InetOrgPerson)(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
关于java - 使用 Spring Security 获取通过 Active Directory 登录的用户的电子邮件地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20290420/