有沒有一種方法可以從自定義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