---
title: "自定义acegi的Authentication对象"
author: "weishuwei"
date: "2007-05-21T14:43:06Z"
tags: ["Acegi", "Security"]
categories: ["企业架构"]
slug: "acegi-authentication"
draft: false
lastmod: "2007-05-21T14:43:06Z"
id: 81554
url: "https://weishuwei.iteye.com/blog/81554"
---

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

01. @Override
02. public String execute() throws Exception {
03. username="admin001";
04. password="password";
05. UsernamePasswordAuthenticationToken authen = new UsernamePasswordAuthenticationToken(username, password);
06. HttpServletRequest request = ServletActionContext.getRequest();
07. HttpServletResponse response = ServletActionContext.getResponse();
08. // 保存用户名到session里
09. 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. }