在spring security手动 自定义 用户认证 SecurityContextHolder

//从spring容器中获取UserDetailsService(这个从数据库根据用户名查询用户信息,及加载权限的service)

UserDetailsService userDetailsService =

      (UserDetailsService)SpringContextUtil.getBean("userDetailsService");

 

//根据用户名username加载userDetails

UserDetails userDetails = userDetailsService.loadUserByUsername(username);

 

//根据userDetails构建新的Authentication,这里使用了

//PreAuthenticatedAuthenticationToken当然可以用其他token,如UsernamePasswordAuthenticationToken              

PreAuthenticatedAuthenticationToken authentication =

      new PreAuthenticatedAuthenticationToken(userDetails, userDetails.getPassword(),userDetails.getAuthorities());

 

//设置authentication中details

authentication.setDetails(new WebAuthenticationDetails(request));

 

//存放authentication到SecurityContextHolder

SecurityContextHolder.getContext().setAuthentication(authentication);

HttpSession session = request.getSession(true);

//在session中存放security context,方便同一个session中控制用户的其他操作

session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());

 

 

 

 

 

/**

 * 获取用户Details信息的回调函数.

 */

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,DataAccessException {

    GeOperator geOperator = geOperatorService.findOperatorByPK(username);

    if(geOperator == null){

        throw new UsernameNotFoundException("","用户名错误");

    }

    //加载该用户权限

    Set grantedAuths = obtainGrantedAuthorities(geOperator);

    boolean enabled = true;

    boolean accountNonExpired = true;

    boolean credentialsNonExpired = true;

    boolean accountNonLocked = true;

    UserDetails userdetails = new MisUser(username, geOperator.getPwd(),

            geOperator, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);

     return userdetails;

}

你可能感兴趣的:(在spring security手动 自定义 用户认证 SecurityContextHolder)