【发布时间】:2011-12-24 20:15:25
【问题描述】:
有没有办法在自定义数据源中从 WebApplicationContext 访问 HttpSession?我实现了一个自定义身份验证处理过滤器,它将一些信息存储在 HttpSession 中。然后,DataSource 使用此信息来获取数据库连接。
另一种选择是使用 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 的新类,它只有用户名和密码。然后将 ThreadLocal 重新创建为实用程序接口的静态最终变量:
public interface WebUtils{
public static final ThreadLocal<AuthInfo> authInfo = new ThreadLocal<AuthInfo>();
}
ThreadLocal的值然后在filter的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一样吗?
【问题讨论】:
标签: java spring spring-security datasource