我一直在寻找一种方法来为每个请求重新加载Spring Security UserDetails对象,并且无法在任何地方找到示例。
有谁知道怎么做这样的事情?
基本上,我们希望每次请求都重新加载用户权限,因为该用户的权限可能会从Web请求更改为Web请求。
例如,用户已登录并随后被授予新权限(并通知他们通过电子邮件获得新权限),我知道该用户实际获得该新权限的唯一方法是通过记录然后重新登录。我想尽可能避免。
感谢任何友好的建议。
答案 0 :(得分:7)
最后,在两年之后,针对上述问题以及this question之后的六年,这里是关于如何使用Spring为每个请求重新加载用户的UserDetails的答案...
要为每个请求重新加载用户/安全上下文,重要的是覆盖Spring Security HttpSessionSecurityContextRepository的默认行为,该行为实现SecurityContextRepository接口。
HttpSessionSecurityContextRepository是Spring Security用于从HttpSession获取用户安全上下文的类。调用此类的代码是将SecurityContext放在threadlocal上的代码。因此,当调用loadContext(HttpRequestResponseHolder requestResponseHolder)
方法时,我们可以转向并向DAO或Repository发出请求并重新加载用户/主体。
一些尚未完全弄清楚的关注事项。
此代码线程是否安全?
我不知道,这取决于每个线程/请求是否在Web服务器中创建了新的SecurityContext。如果有一个新的SecurityContext创建生活是好的,但如果没有,可能会有一些有趣的意外行为,如陈旧的对象异常,用户/主体被保存到数据存储的错误状态等等。
我们的代码“风险足够低”,我们还没有尝试过测试潜在的多线程问题。
每次请求调用数据库是否会影响性能?
最有可能,但我们的Web服务器响应时间没有发生明显变化。
关于这个主题的几个快速说明......
我们从这一变化中获得的好处:
守则
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.openid.OpenIDAuthenticationToken;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import xxx.repository.security.UserRepository;
import xxx.model.security.User;
import xxx.service.security.impl.acegi.AcegiUserDetails;
public class ReloadUserPerRequestHttpSessionSecurityContextRepository extends HttpSessionSecurityContextRepository {
// Your particular data store object would be used here...
private UserRepository userRepository;
public ReloadUserPerRequestHttpSessionSecurityContextRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
// Let the parent class actually get the SecurityContext from the HTTPSession first.
SecurityContext context = super.loadContext(requestResponseHolder);
Authentication authentication = context.getAuthentication();
// We have two types of logins for our system, username/password
// and Openid, you will have to specialize this code for your particular application.
if (authentication instanceof UsernamePasswordAuthenticationToken) {
UserDetails userDetails = this.createNewUserDetailsFromPrincipal(authentication.getPrincipal());
// Create a new Authentication object, Authentications are immutable.
UsernamePasswordAuthenticationToken newAuthentication = new UsernamePasswordAuthenticationToken(userDetails, authentication.getCredentials(), userDetails.getAuthorities());
context.setAuthentication(newAuthentication);
} else if (authentication instanceof OpenIDAuthenticationToken) {
UserDetails userDetails = this.createNewUserDetailsFromPrincipal(authentication.getPrincipal());
OpenIDAuthenticationToken openidAuthenticationToken = (OpenIDAuthenticationToken) authentication;
// Create a new Authentication object, Authentications are immutable.
OpenIDAuthenticationToken newAuthentication = new OpenIDAuthenticationToken(userDetails, userDetails.getAuthorities(), openidAuthenticationToken.getIdentityUrl(), openidAuthenticationToken.getAttributes());
context.setAuthentication(newAuthentication);
}
return context;
}
private UserDetails createNewUserDetailsFromPrincipal(Object principal) {
// This is the class we use to implement the Spring Security UserDetails interface.
AcegiUserDetails userDetails = (AcegiUserDetails) principal;
User user = this.userRepository.getUserFromSecondaryCache(userDetails.getUserIdentifier());
// NOTE: We create a new UserDetails by passing in our non-serializable object 'User', but that object in the AcegiUserDetails is transient.
// We use a UUID (which is serializable) to reload the user. See the userDetails.getUserIdentifier() method above.
userDetails = new AcegiUserDetails(user);
return userDetails;
}
}
要使用xml配置插入新的SecurityContextRepository,只需在security:http上下文中设置security-context-repository-ref属性。
示例xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<security:http context-repository-ref="securityContextRepository" >
<!-- intercept-url and other security configuration here... -->
</security:http>
<bean id="securityContextRepository" class="xxx.security.impl.spring.ReloadUserPerRequestHttpSessionSecurityContextRepository" >
<constructor-arg index="0" ref="userRepository"/>
</bean>
</beans>
答案 1 :(得分:1)
您好,我想与基于令牌的身份验证分享与此问题相关的内容,在我的案例中是Oauth2。起初我尝试了上面的hooknc的方法,在我的情况下我使用基于令牌的身份验证,所以我的身份验证对象是instanceOf Oauth2Authentication。与标准身份验证主体不同,Oauth2Authentication对象由授权请求和身份验证对象构成。此外,通过使用令牌本身构造主体。因此,当尝试在另一个调用中重用该令牌时,它最终会以原始用户数据结束。因此,此方法不适用于基于令牌的身份验证。
我的原始问题要明确是在用户更新用户设置之后,如果用户之后会进行其他API调用,则会产生旧的用户信息。我没有尝试更新主体,而是发现在更新后发布新令牌是一种更好的方法。
我还应该补充一点,我的Authentication Oauth2方案完全没有状态,一切都存储在DB中。
答案 2 :(得分:0)
我要使用FilterSecurityInterceptor的重新验证技巧
用于使用JDBC userDetailsService的表单登录
AuthenticationProvider
验证为false。
package studying.spring;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
public class MyDaoAuthenticationProvider extends DaoAuthenticationProvider {
@Override
protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
Authentication result = super.createSuccessAuthentication(principal, authentication, user);
result.setAuthenticated(false);
return result;
}
}
AuthenticationEntryPoint for ExceptionTranslationFilter
注销并重定向到登录页面。
package studying.spring;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
public class MyLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
public MyLoginUrlAuthenticationEntryPoint(String loginFormUrl) {
super(loginFormUrl);
}
@Override
protected String determineUrlToUseForThisRequest(
HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
if (exception != null) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
new SecurityContextLogoutHandler().logout(request, response, auth);
SecurityContextHolder.getContext().setAuthentication(null);
}
return super.determineUrlToUseForThisRequest(request, response, exception);
}
}
<强>根context.xml中强>
rase-credentials attr。为假。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<security:http entry-point-ref="myLoginUrlAuthenticationEntryPoint">
<security:intercept-url pattern="/**" access="hasRole('USER')"/>
<security:form-login/>
<security:logout/>
</security:http>
<security:authentication-manager erase-credentials="false">
<security:authentication-provider ref="myDaoAuthenticationProvider"/>
</security:authentication-manager>
<bean id="myLoginUrlAuthenticationEntryPoint" class="studying.spring.MyLoginUrlAuthenticationEntryPoint">
<constructor-arg name="loginFormUrl" value="/login" />
</bean>
<bean id="myDaoAuthenticationProvider" class="studying.spring.MyDaoAuthenticationProvider">
<property name="userDetailsService" ref="jdbcDaoImpl" />
</bean>
<bean id="jdbcDaoImpl" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">
<property name="dataSource" ref="securityDataSource" />
</bean>
<bean id="securityDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/studying_spring_security" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
</beans>
答案 3 :(得分:0)
对于管理员用户而言,更改其他用户的权限:您可以尝试检索受影响用户的会话并设置一些属性以指示需要重新加载。
如果您碰巧将Spring Session的会话属性保留在数据库中(例如,以支持多个容器实例),则可以标记活动会话以在管理员用户更改权限时重新加载:
$(document).ready(function() {
$('.thumbs img').click(function(){
$this = $(this);
$parent = $this.parent('.thumbs');
$previous = $parent.prev();
$previous.attr('src',$this.attr('src').replace('thumb','large'));
});
});
对于已登录的用户端:您可以编写Spring Security过滤器,该过滤器将检查会话属性,以是否重新加载当前会话的身份验证。如果管理员已将其标记为要重新加载,我们将再次从数据库中检索@Autowired
private FindByIndexNameSessionRepository<Session> sessionRepo;
public void tag(String username) {
Map<String, Session> sessions = sessionRepo.findByIndexNameAndIndexValue
(FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username);
for (Session s : sessions.values()) {
s.setAttribute("reloadAuth", true);
sessionRepo.save(s);
}
}
,然后重新设置Principal
。
Authentication