2014-11-03 296 views
1

我正在使用Spring安全性進行身份驗證的Spring-MVC應用程序。爲了訪問安全功能,用戶必須登錄。我正在使用可以確定用戶是否已登錄的功能。Spring Security如何區分多個登錄用戶

我只是想知道下面發佈的代碼是否適用於多個用戶同時登錄,以區分用戶A是否已登錄。如果不是,請提供任何解決方案或想法。謝謝。

Person Controller : 
@Controller 
public class PersonController { 

    private PersonService personService; 

// Now whenever there are secure functions to be accessed, like below, I use it the following way : 
} 
    @RequestMapping(value = "/note/list/{id}",method = RequestMethod.GET) 
    public String listNotes(@ModelAttribute("notices") Notes p,@PathVariable int id,Model model) { 
Person person = personService.getCurrentlyAuthenticatedUser(); 
model.addAttribute("section1",this.notesService.listNotesBySectionId(1,person)); 
} 

目前獲得認證的用戶功能:

@Override 
    public Person getCurrentlyAuthenticatedUser() { 
     Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
     String authenticatedUserId = authentication.getName(); 

     Person person = personDAO.findPersonByUsername(authenticatedUserId); 
     return person; 
    } 

我實現認證是這樣的:

@Transactional 
@Service("userDetailsService") 
public class LoginServiceImpl implements UserDetailsService{ 

    @Autowired private PersonDAO personDAO; 
    @Autowired private Assembler assembler; 

    private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER"); 

    @Override 
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,DataAccessException { 
     Person person = personDAO.findPersonByUsername(username); 
      if(person == null) { throw new UsernameNotFoundException("Wrong username or password");} //Never specify which one was it exactly 
     return assembler.buildUserFromUserEntity(person); 
    } 
} 

裝配用戶

@Transactional 
@Service("userDetailsService") 
public class LoginServiceImpl implements UserDetailsService{ 

    @Autowired private PersonDAO personDAO; 
    @Autowired private Assembler assembler; 

    private static final GrantedAuthority USER_AUTH = new SimpleGrantedAuthority("ROLE_USER"); 

    @Override 
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,DataAccessException { 
     Person person = personDAO.findPersonByUsername(username); 
      if(person == null) { throw new UsernameNotFoundException("Wrong username or password");} 
     return assembler.buildUserFromUserEntity(person); 
    } 
} 

回答

2

SecurityContextHolder的內部是implem擁有一個ThreadLocal。這是Spring安全使用的默認策略,適用於Web應用程序。 由於ThreadLocal與當前線程的範圍隔離,因此無論當前登錄的其他人有多少,您的代碼都只能訪問當前用戶的信息。

但是,在您的代碼中,您應該檢查空認證對象,除非您已啓用匿名身份驗證。

String authenticatedUserId = authentication.getName(); 

驗證在上面的行中可能爲空。

+0

謝謝你的詳細解答。所以結論是上面的代碼可以處理多重認證。我會檢查字符串是否爲空。 – 2014-11-03 15:40:08

+0

除了身份驗證之外,還沒有運行您的代碼以查看它是否無錯。我只是說,春季安全處理這個開箱即用。 – grid 2014-11-03 15:43:19

+0

此時,代碼不會引發錯誤,用戶登錄後,我也可以獲取當前登錄的用戶和所有用戶。我忘了處理空認證部分...任何想法我怎麼處理這個異常。我不想顯示一些Apache錯誤頁面。 – 2014-11-03 15:50:56