2016-02-29 113 views

回答

0

如果您的UserDetailsS​​ervice实现UserDetailsManager,只需使用loadUserByUsername方法加载你需要的数据。

UserDetails loadUserByUsername(String username) throws UsernameNotFoundException; 

您可以使用@Autowired工作再上一个数据源访问来获取数据。

+0

的loadUserByUsername方法将返回的UserDetails。包含用户名,密码和权限。无法获取branch_id。 –

+0

@Autowired 私人HttpServletRequest请求; 使用上面的代码我创建一个会话属性,并将branch_id设置为该对象。 –

+0

如果您实现UserDetails,则可以存储自定义数据,然后使用** loadUserByUsername **返回它(请参阅@jlumietu答案)。没有必要为会话设置新的属性。 –

1
Add the following listner to web.xml 

<listener> 
    <listener-class> 
org.springframework.web.context.request.RequestContextListener 
</listener-class> 
</listener> 

then add the following code to your userdetailsservice implimentation class. 

@Autowired 
private HttpServletRequest request; 

then you can set session attribute inside the 
public UserDetails loadUserByUsername(String username){} method. 

request.getSession().setAttribute("branchId", employeeVO.getBranch_id()); 
0

为什么你不创建一个UserDetails的实现,它包括你需要的所有字段?

如果您已经创建了UserDetailsS​​ervice,那么返回另一种类型的UserDetails非常简单。然后它可以保存在您正在使用的Authentication类中,也可以将其保存到details属性中。

编辑:

public class MyUserDetails implements UserDetails{ 

     private Object branchId; 

     /** 
     * @return the branchId 
     */ 
     public Object getBranchId() { 
      return branchId; 
     } 

     /** 
     * @param branchId the branchId to set 
     */ 
     public void setBranchId(Object branchId) { 
      this.branchId = branchId; 
     } 

     //@Override other methods 

} 

然后在你的UserDetailsS​​ervice创造者的一个实例实现类

public class MyUserDetailsService implements UserDetailsService { 

    /* (non-Javadoc) 
    * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String) 
    */ 
    @Override 
    public UserDetails loadUserByUsername(String arg0) 
      throws UsernameNotFoundException { 
     MyUserDetailsuserDetails = new MyUserDetails(); 
     ... 
     userDetails.setBranchId(theBranchId); 

     return userDetails; 
    } 
+0

UserDetailsS​​ervice接口是Spring安全性提供的默认接口。我创建了一个实现UserDetailsS​​ervice并覆盖默认方法的实现类。 –

+0

这就是我的意思。如果你正在创建你自己的UserDetailsS​​ervice实现,为什么不让它返回一个你需要的所有属性的UserDetails实现类? – jlumietu

相关问题