2011-02-06 85 views
3


我有以下UserDetailsS​​ervice實現。
到目前爲止,身份驗證過程運行良好。
如何將我的「MYUSER豆」(即成功登錄)存儲在「會話」,所以我可以在我的應用彈簧安全訪問來自更深層的UserDetailsS​​ervice

感謝訪問它在其他領域。

@Transactional(readOnly = true) 
public class CustomUserDetailsService implements UserDetailsService { 


    private EmployeesApi employeesApi = new EmployeesApi(); 

    /** 
    * Retrieves a user record containing the user's credentials and access. 
    */ 
    public UserDetails loadUserByUsername(String userName) 
      throws UsernameNotFoundException, DataAccessException { 

     // Declare a null Spring User 
     UserDetails user = null; 

     try { 


      MyUser employee = employeesApi.getByUserName(userName); 



      user = new User(
        employee.getUserName(), 
        employee.getPassword().toLowerCase(), 
        true, 
        true, 
        true, 
        true, 
        getAuthorities(1)); 

     } catch (Exception e) { 
      logger.error("Error in retrieving user"); 
      throw new UsernameNotFoundException("Error in retrieving user"); 
     } 


    } 
    .... 

回答

6

Spring Security已經在會話中爲您存儲了已認證用戶的UserDetails

因此,存儲MyUser在會話中的最簡單的方法是實現包含MyUser參考定製UserDetails

public class MyUserDetails extends User { 
    private MyUser myUser; 
    public MyUserDetails(..., MyUser myUser) { 
     super(...); 
     this.myUser = myUser; 
    } 
    public MyUser getMyUser() { 
     return myUser; 
    } 
    ... 
} 

從你UserDetailsService返回它:

MyUser employee = employeesApi.getByUserName(userName); 
user = new MyUserDetails(..., myUser); 

然後你可以通過安全上下文輕鬆訪問MyUser

MyUser myUser = ((MyUserDetails) SecurityContextHolder 
    .getContext().getAuthentication().getPrincipal()).getMyUser(); 

在Spring MVC控制器:

@RequestMapping(...) 
public ModelAndView someController(..., Authentication auth) { 
    MyUser myUser = ((MyUserDetails) auth.getPrincipal()).getMyUser(); 
    ... 
} 

在JSP:

<security:authentication var = "myUser" property="principal.myUser" /> 
+0

對不起,我不明白,你可以發佈簡單的例子? TX! – fatnjazzy 2011-02-06 12:34:18

相關問題