是的,预身份验证方案正是您所需要的。
似乎这些对象将在主体已经处于会话中时使用,由某些先前的身份验证机制放置(是吗?)。
并非如此,您可以根据需要使用预身份验证
PreAuthenticatedAuthenticationToken从请求中创建。只是做我的另外一个问题说明几件事情。
首先扩展
AbstractPreAuthenticatedProcessingFilter以从请求中获取用户名和角色:
public class MyPreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter { public MyPreAuthenticatedProcessingFilter( AuthenticationManager authenticationManager) { setAuthenticationDetailsSource(new MyAuthenticationDetailsSource()); } @Override protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) { return "Anonymous"; } @Override protected Object getPreAuthenticatedCredentials(HttpServletRequest request) { return "N/A"; } public static class MyAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, MySessionUserDetails> { // roles probably should be encrypted somehow static final String ROLES_PARAMETER = "pre_auth_roles"; @Override public MySessionUserDetails buildDetails(HttpServletRequest req) { // create container for pre-auth data return new MySessionUserDetails(req.getParameter(ROLES_PARAMETER)); } }}MySessionUserDetails类将使用角色将spring拆分为List of
SimpleGrantedAuthority或任何其他
GrantedAuthority实现。另外,推荐使用List并优于List
GrantedAuthority[]。
二,实施
AuthenticationUserDetailsService:
public class MyPreAuthenticatedUserDetailsService implements AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> { @Override public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token) throws UsernameNotFoundException { MySessionUserDetails sessionUserDetails = (MySessionUserDetails) token.getDetails(); List<GrantedAuthority> authorities = sessionUserDetails.getAuthorities(); return new User(token.getName(), "N/A", true, true, true, true, authorities); }}然后在XML连接块中:
<security:http use-expressions="true"> <security:intercept-url pattern="/**" access="isAuthenticated()" /> <security:custom-filter position="PRE_AUTH_FILTER" ref="myPreAuthenticationFilter" /></security:http><bean id="myPreAuthenticationFilter" > <property name="authenticationManager" ref="authenticationManager" /></bean><bean id="preauthAuthProvider" > <property name="preAuthenticatedUserDetailsService"> <bean /> </property></bean><security:authentication-manager alias="authenticationManager"> <security:authentication-provider ref="preauthAuthProvider" /></security:authentication-manager>
瞧!您应该具有
User在应用程序中使用的经过身份验证的主体。
我在这里编写的代码需要Spring Security 3.1,如果您要使用它,我强烈建议您使用它(它确实需要Spring
3.0.7+)。另外,Spring Security参考手册是您的朋友!



