在spring security中创建一个会话范围的bean

时间:2015-12-03 05:42:41

标签: spring-mvc spring-security

我需要创建一个POJO类来存储与用户有关的信息。在spring security中,我的权限表有一列额外的instituionIds,它是一个CSV字符串,在各种DAO调用中都需要。我需要设置这个类的值,这在查询数据库时是必需的。

@Component
@Scope("session")
public class InstitutionList {

    private String institutionList = "";

    public String getInstitutionList() {
        return institutionList;
    }

    public void setInstitutionList(String institutionList) {
        this.institutionList = institutionList;
    }
}

我需要在我的自定义UserDetailsS​​ervice实现中使用它

@Transactional
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);
    private @Autowired ACSAdminUsersService acsAdminUsersService;
    private @Autowired ACSAdminAuthoritiesService acsAdminAuthoritiesService;
    private String[] authority;

    public ACSAdminUsers getUserByAdminUsername(String username) {
        logger.info("Getting user by username");
        ACSAdminUsers user = acsAdminUsersService.getUserByAdminUsername(username);
        if(user!=null) acsAdminUsersService.addLogInInfo(username);
        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ACSAdminUsers user = getUserByAdminUsername(username);
        logger.info("Username is : " + username);
        logger.info("user is : " + user);

        authority = acsAdminAuthoritiesService.getAuthoritiesForRole(user.getRole());
        logger.info("User role is : " + authority);
        if(authority == null) {
            throw new UsernameNotFoundException("User : "+username+" has no authorities." );
        }else {
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        return new org.springframework.security.core.userdetails.User(username,user.getAdmin_pass(),
                true,accountNonExpired,credentialsNonExpired,
                accountNonLocked,
                getAuthorities(username));
        }
    }

    public Collection<? extends GrantedAuthority> getAuthorities(String username) {
        List<GrantedAuthority> authList = null;

        authList=new ArrayList<GrantedAuthority>();

        for(int i = 0; i < authority.length; i++) {
            SimpleGrantedAuthority s = new SimpleGrantedAuthority(this.authority[i]);
            authList.add(s);
        }
        return authList;
    }
}

在上面的java类中,我需要查询数据库并获取权限,以及需要在整个应用程序中的查询中使用的INSTITIds。

1 个答案:

答案 0 :(得分:0)

您可以创建自己的InstitutionContextHolder并使用threadlocal来存储对象。通过这种方式,您可以在所需的每个类中访问此对象。您可以查看SecurityContextHolder的示例。