【问题标题】:Spring security custom authentication how to access firstname and lastnameSpring security自定义身份验证如何访问名字和姓氏
【发布时间】:2014-04-13 22:50:14
【问题描述】:

我正在使用凭据和 IP 地址进行自定义身份验证,但是,我需要在 UI 上显示用户名和姓。虽然我没有使用 UserDetails 并且我使用的是 UsernamePasswordAuthenticationToken,但我如何才能访问 firstname 和 lastname,其中 UserDetails bean 保存在 Details 中。

Account account = (Account)accountDao.loadUserByUsername(username);
    if(!account.getPassword().equals(password)) {
        logger.debug("[USER AUTHENTICATION]Invalid Password:"+password);
        return null;
    }
    logger.warn(String.format("[USER AUTHENTICATION]%s %s",new Object[]{account.getFirstName(),account.getLastName()}));
    isAuthenticatedByIP = false;

    for(AllowedIPAddress allowedIpAddress:account.getAllowedIPs()){
        if(allowedIpAddress.getIpAddress().equals("0.0.0.0")||allowedIpAddress.getIpAddress().equals(userIPAddress)) {
            isAuthenticatedByIP = true;
            break;
        } 
    }


    // Authenticated, the user's IP address matches one in the database
    if (isAuthenticatedByIP)
    {

        logger.debug("[USER AUTHENTICATION]isAuthenticatedByIP is true, IP Addresses match");

UsernamePasswordAuthenticationToken result = null;

result = new  UsernamePasswordAuthenticationToken(account.getUsername(), account.getPassword(), account.getAuthorities()) ;

result.setDetails(account);
return result
} else {
  logger.warn("[USER AUTHENTICATION]User IP not allowed "+userIPAddress);
}

如何在 jsp 中获取帐户字段以显示用户的欢迎消息。

【问题讨论】:

  • 你实现UserDetailsService来获取org.springframework.security.core.userdetails.UserDetails对象
  • @SantoshJoshi 我更新了上面的代码,其中帐户是 UserDetails 的实例

标签: java spring spring-mvc spring-security


【解决方案1】:

在 spring mvc 中,您可以将自定义 userDetail bean 作为会话范围的 bean,并在成功登录后在其中设置所需的值,例如名字、姓氏等。在任何地方使用该值。

【讨论】:

  • 我正在使用 Spring MVC 和 Spring Security
  • @user3364699 您可以在会话范围内根据您的要求制作一个 pojo 类。请参阅我的回答已经建议您。先尝试然后告诉您是否有任何问题。
猜你喜欢
  • 2014-04-20
  • 2014-12-13
  • 2016-09-05
  • 1970-01-01
  • 2016-08-05
  • 2020-12-05
  • 2015-04-27
  • 2013-02-18
  • 1970-01-01
相关资源
最近更新 更多