项目中有时需要自己定义一下acegi的Authentication对象,经过分析源码,现给出实现代码如下所示:
- @Override
- public String execute() throws Exception {
- username="admin001";
- password="password";
- UsernamePasswordAuthenticationToken authen = new UsernamePasswordAuthenticationToken(username, password);
- HttpServletRequest request = ServletActionContext.getRequest();
- HttpServletResponse response = ServletActionContext.getResponse();
-
- request.getSession().setAttribute(ACEGI_SECURITY_LAST_USERNAME_KEY, username);
- WebAuthenticationDetails webdetails=new WebAuthenticationDetails(request);
-
- authen.setDetails(webdetails);
-
- Authentication auth1=authenticationManager.doAuthentication(authen);
- SecurityContextHolder.getContext().setAuthentication(auth1);
- rememberMeServices.loginSuccess(request, response, auth1);
- if(auth1.getDetails()!=null ){
- System.out.println("auth1details");
- if(auth1.getDetails() instanceof WebAuthenticationDetails){
- WebAuthenticationDetails dt=(WebAuthenticationDetails)auth1.getDetails();
- System.out.println(dt.getSessionId());
- }
- }
- System.out.println("认证是否通过: "+auth1.isAuthenticated());
- Object principal=SecurityContextHolder.getContext().getAuthentication().getPrincipal();
- if(principal instanceof UserDetails){
- UserDetails user=(UserDetails)principal;
- if(this.userCache.getUserFromCache(user.getUsername())!=null){
- System.out.println("usercache is not null");
- }else{
- this.userCache.putUserInCache(user);
- }
- }
- if (UserSecurty.getUserDetails() != null) {
- System.out.println(UserSecurty.getUserName());
- System.out.println(UserSecurty.getUserDetails().getPassword());
- System.out.println(UserSecurty.getUserDetails().getAuthorities());
- for(GrantedAuthority authority:UserSecurty.getUserDetails().getAuthorities()){
- System.out.println("权限: "+authority);
- }
- }
- return NONE;
-
- }