ITeye博客

自定义acegi的Authentication对象

weishuwei · 2007-05-21 14:43 · 权限管理 · 企业架构 · Markdown

项目中有时需要自己定义一下acegi的Authentication对象,经过分析源码,现给出实现代码如下所示:

  1. @Override
  2. public String execute() throws Exception {
  3. username="admin001";
  4. password="password";
  5. UsernamePasswordAuthenticationToken authen = new UsernamePasswordAuthenticationToken(username, password);
  6. HttpServletRequest request = ServletActionContext.getRequest();
  7. HttpServletResponse response = ServletActionContext.getResponse();
  8. // 保存用户名到session里
  9. request.getSession().setAttribute(ACEGI_SECURITY_LAST_USERNAME_KEY, username);
  10. WebAuthenticationDetails webdetails=new WebAuthenticationDetails(request);
  11. //注意:这里setDetails的对象一定要是WebAuthenticationDetails
  12. authen.setDetails(webdetails);
  13. //这里验证不通过会返回null对象
  14. Authentication auth1=authenticationManager.doAuthentication(authen);
  15. SecurityContextHolder.getContext().setAuthentication(auth1);
  16. rememberMeServices.loginSuccess(request, response, auth1);
  17. if(auth1.getDetails()!=null ){
  18. System.out.println("auth1details");
  19. if(auth1.getDetails() instanceof WebAuthenticationDetails){
  20. WebAuthenticationDetails dt=(WebAuthenticationDetails)auth1.getDetails();
  21. System.out.println(dt.getSessionId());
  22. }
  23. }
  24. System.out.println("认证是否通过: "+auth1.isAuthenticated());
  25. Object principal=SecurityContextHolder.getContext().getAuthentication().getPrincipal();
  26. if(principal instanceof UserDetails){
  27. UserDetails user=(UserDetails)principal;
  28. if(this.userCache.getUserFromCache(user.getUsername())!=null){
  29. System.out.println("usercache is not null");
  30. }else{
  31. this.userCache.putUserInCache(user);
  32. }
  33. }
  34. if (UserSecurty.getUserDetails() != null) {
  35. System.out.println(UserSecurty.getUserName());
  36. System.out.println(UserSecurty.getUserDetails().getPassword());
  37. System.out.println(UserSecurty.getUserDetails().getAuthorities());
  38. for(GrantedAuthority authority:UserSecurty.getUserDetails().getAuthorities()){
  39. System.out.println("权限: "+authority);
  40. }
  41. }
  42. return NONE;
  43. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。