gpt4 book ai didi

java - 如何在 Spring 中从自定义数据源访问 Http Session?

转载 作者:行者123 更新时间:2023-12-02 08:02:58 25 4
gpt4 key购买 nike

有没有办法从自定义数据源中的 WebApplicationContext 访问 HttpSession?我实现了一个自定义身份验证处理过滤器,它在 HttpSession 中存储一些信息。然后,数据源使用此信息来获取数据库连接。

另一个选项是使用 SecurityContextHolder 来获取经过自定义以包含其他属性的身份验证 token 。我不确定这是否是正确的方法。

这是我到目前为止所拥有的:

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创建为实用程序接口(interface)的静态最终变量:

public interface WebUtils{
public static final ThreadLocal<AuthInfo> authInfo = new ThreadLocal<AuthInfo>();
}

然后在过滤器的attemptAuthentication方法中设置ThreadLocal的值

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 相同吗?

最佳答案

在典型的多层应用程序中,您的数据访问层不应该了解更高层(例如 HTTP 接口(interface))。

我建议您使用 Spring 的 session 请求范围进行调查。您可以在这些范围之一中创建一个范围代理 bean,将身份验证信息放入其中,然后将其注入(inject)到数据源中。

关于java - 如何在 Spring 中从自定义数据源访问 Http Session?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8623567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com