SpringSecurity - 禁用执行“虚假登录”的最佳方法

时间:2012-10-25 10:37:38

标签: spring-security

我想找到最佳/优雅/方便的方法来启用/禁用测试和开发环境的弹簧安全性。我想在db上使用属性,如果此属性设置为ON,则认证是必需的,否则用户无需进行身份验证,并且直接到达应用程序主页,并且所有角色都关联,并且伪用户名/属性。< / p>

顺便说一句,我的应用程序有一个简单的身份验证策略:用户之前通过不同的Web应用程序登录,该应用程序为他提供了访问许多其他Web应用程序的链接。其中一个链接重定向到我的网络应用程序,其中包含用户名和角色的简单提交,我的安全链捕获此信息并执行自动身份验证。

任何建议都将受到赞赏;)

再见! Dolfiz

我的代码的一些片段......

SpringSecurityContext.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-3.0.xsd
          http://www.springframework.org/schema/security
          http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <security:http use-expressions="true" auto-config="false" entry-point-ref="preAuthenticatedProcessingFilterEntryPoint">
        <security:intercept-url pattern="/fakeLogin*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
        <security:intercept-url pattern="/authError*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
        <security:intercept-url pattern="/VAADIN**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
        <security:intercept-url pattern="/**" access="isAuthenticated()" />
        <security:logout logout-url="/logout" logout-success-url="http://milan-ias-vs.usersad.everis.int/DMTest/" invalidate-session="true" />
        <security:custom-filter position="PRE_AUTH_FILTER" ref="preAuthenticatedProcessingFilter" />
    </security:http>

    <bean id="preAuthenticatedProcessingFilterEntryPoint" class="it.ram.authentication.LinkForbiddenEntryPoint" />

    <bean id="preAuthenticatedProcessingFilter" class="it.ram.authentication.PreAuthenticatedProcessingFilter">
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>

    <bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
        <property name="preAuthenticatedUserDetailsService">
            <bean class="it.ram.authentication.PreAuthenticatedUserDetailsService" />
        </property>
    </bean>

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider ref="preauthAuthProvider" />
    </security:authentication-manager>

</beans>

PreAuthenticatedProcessingFilter.java:

public class PreAuthenticatedProcessingFilter extends AbstractPreAuthenticatedProcessingFilter {

    private final static Log log = LogFactory.getLog(PreAuthenticatedProcessingFilter.class);

    public PreAuthenticatedProcessingFilter() {
        super();
        log.debug("PreAuthenticatedProcessingFilter default constructor");
        setAuthenticationDetailsSource(new CustomAuthenticationDetailsSource());
    }

    public PreAuthenticatedProcessingFilter(AuthenticationManager authenticationManager) {
        log.debug("PreAuthenticatedProcessingFilter constructor with AuthMan arg");
        setAuthenticationDetailsSource(new CustomAuthenticationDetailsSource());
    }

    @Override
    protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
        String userName = request.getParameter(Constants.REQUEST_USER_PARAM);
        log.debug("getPreAuthenticatedPrincipal - Returning " +userName);
        return userName;
    }

    @Override
    protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
        log.debug("getPreAuthenticatedCredentials - Returning N/A");
        return "N/A";
    }

    public static class CustomAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, SessionUserDetails> {

        @Override
        public SessionUserDetails buildDetails(HttpServletRequest request) {
            log.debug("buildDetails");
            // create container for pre-auth data
            String role = request.getParameter(Constants.REQUEST_ROLE_PARAM);
            return new SessionUserDetails(role);
        }
    }
}

PreAuthenticatedUserDetailsS​​ervice.xml:

public class PreAuthenticatedUserDetailsService implements AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> {

    private final static Log log = LogFactory.getLog(PreAuthenticatedUserDetailsService.class);

    @Override
    public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken  token) throws UsernameNotFoundException {
        log.debug("loadUserDetails - token.getName(): " +token.getName());

        SessionUserDetails sessionUserDetails = (SessionUserDetails) token.getDetails();
        List<SimpleGrantedAuthority> authorities = sessionUserDetails.getAuthorities();            
        return new User(token.getName(), "N/A", true, true, true, true, authorities);
    }

}

1 个答案:

答案 0 :(得分:0)

看看:

org.springframework.security.web.authentication.RememberMeServices #autoLogin(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

在这里寻找实施方案:

http://git.springsource.org/spring-security/spring-security/trees/c12c43da9eb59b664bc995a38859c6acac621390/web/src/main/java/org/springframework/security/web/authentication/rememberme

SecurityContextHolder是您拥有现有凭据然后更改或替换它们的地方。

SecurityContext securityContext = SecurityContextHolder.getContext();
Authentication authentication = securityContext.getAuthentication();
// authentication contains existing (if set and non-null) maybe it is anonymous
// so then you might have a better set of credentials to replace it with
WebappUserDetails webappUserDetails = userContextService.getPrincipal(WebappUserDetails.class);
// The above constructs my custom type that implement spring UserDetails interface
// this is the identity of the user
// You should check things are valid (account enable and valid, etc..)
// Then you make a fake Authentication and attach it to the session context
// There are many token kinds in spring representing different ways to auth
//  this token is the kind that might be used for a HTML form based login with
//  username and password. 
String principal = "myusername";  // username
String credentials = "mypassword";  // password
// Note you should probably not want to hardwire passwords into code and the correct
//  way is to setup a new Token type and configure main security XML to allow it
//  to the secure URLs (or secured subjects)
Authentication authRequest = new UsernamePasswordAuthenticationToken(principal, credentials);
Authentication authResult = authenticationManager.authenticate(authRequest);
// Check the authResult then attach it to the context
SecurityContextHolder.getContext().setAuthentication(authResult);