有没有一种方法可以从自定义DataSource中的WebApplicationContext访问HttpSession?我实现了一个定制的认证处理过滤器,它在HttpSession中存储了一些信息。这个信息然后被一个DataSource用来获得一个数据库连接。如何从Spring中的自定义数据源访问HttpSession?
另一个选择是使用SecurityContextHolder获取一个自定义的认证令牌,以包含其他属性。我不确定这是否正确。
这是我到目前为止有:
public class CustomDataSource extends DriverManagerDataSource implements ApplicationContextAware {
protected Connection getConnectionFromDriverManager(String url,
Properties props) throws SQLException {
// want to use the web context to get the http session
// Authentication has a getAttribute(String name) method
SecurityContext securityContext = SecurityContextHolder.getContext();
CustomAuthenticationToken authentication = (CustomAuthenticationToken) securityContext.getAuthentication();
Object attribute = authentication.getAttribute("db");
// create a connection object here
Object conn = getConnectionFromAttribute(attribute);
return (Connection)conn;
}
private WebApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = (WebApplicationContext)applicationContext;
}
}
更新:
我定义了一个名为AUTHINFO的新类,其中只有用户名和密码。然后reated一个ThreadLocal作为公用接口的静态最终变量:
public interface WebUtils{
public static final ThreadLocal<AuthInfo> authInfo = new ThreadLocal<AuthInfo>();
}
ThreadLocal的的值然后在过滤器的attemptAuthentication方法设定现在
AuthInfo info = new AuthInfo();
info.setName(username);
info.setPass(password);
WebAttributes.authInfo.set(info);
,在自定义数据源
protected Connection getConnectionFromDriverManager(String url,
Properties props) throws SQLException {
AuthInfo info = WebAttributes.authInfo.get();
Connection conn = getConnFromAuthInfo(info);
return conn;
}
是不是这样使用SecurityContextHolder和CustomAuthenticationToken?
任何好的资源有关使用范围代理豆?另外,访问DataSource中的SecurityContext是不好的做法吗? – suikodian 2011-12-24 09:51:04