2013-03-15 30 views
5

Chúng tôi đang sử dụng bảo mật mùa xuân để xác thực người dùng dựa trên một số chi tiết người dùng (như userid) đến từ ứng dụng bên ngoài và thực hiện ủy quyền bằng cách sử dụng trình giữ ngữ cảnh bảo mật. Chúng tôi đang sử dụng triển khai tùy chỉnh AbstractAuthenticationProcessingFilter và triển khai tùy chỉnh CustomAuthenticationProvider bằng UserDetailsServiceImpl của chúng tôi được chèn vào nhà cung cấp để tìm nạp chi tiết người dùng từ db.Xác thực bằng cách sử dụng CustomAuthenticationProcessingFilter và CustomAuthenticationProvider tùy chỉnh không hoạt động đúng cách

Khi người dùng duy nhất cố gắng đăng nhập, nó hoạt động tốt, đối tượng xác thực được tạo và được đặt chính xác vào SecurityCOntextHolder. Nhưng khi một người dùng khác cố gắng đăng nhập các đối tượng xác thực cũ bị ghi đè bởi một đối tượng mới. Có vẻ như phiên mới không được tạo trên mỗi lần đăng nhập của người dùng.

Việc thực hiện cho bộ lọc và cung cấp dịch vụ cũng giống như dưới đây -

public class DefaultAuthenticationProcessingFilter extends 
    AbstractAuthenticationProcessingFilter { 

private final static Logger logger = LoggerFactory.getLogger(DefaultAuthenticationProcessingFilter.class); 

private static final String INTERCEPTOR_PROCESS_URL = "/sso/landingpage.action"; 

public DefaultAuthenticationProcessingFilter() { 
    super(INTERCEPTOR_PROCESS_URL); 
} 

public DefaultAuthenticationProcessingFilter(
     String defaultFilterProcessesUrl) { 
    super(defaultFilterProcessesUrl); 
    Assert.notNull(defaultFilterProcessesUrl, "Configuration error :: DefaultFilterProcessesUrl must be specified"); 
} 


/** 
* Method to do authentication of user 
*/ 
@Override 
public Authentication attemptAuthentication(HttpServletRequest request, 
     HttpServletResponse response) throws AuthenticationException, 
     IOException, ServletException { 

    logger.info("Authenticating the user ....."); 

    Authentication authResult = null; 
    try { 

     String eid = request.getParameter("EID"); 

     if(StringUtils.isEmpty(eid)) { 
      throw new PreAuthenticatedCredentialsNotFoundException("EID param not found in request."); 
     } 

     String credentials = "NA"; 
     PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken(eid, credentials); 
     authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); 
     authResult = getAuthenticationManager().authenticate(authRequest); 
    } catch (AuthenticationException e) { 
     unsuccessfulAuthentication(request, response, e); 
    } 
    return authResult; 
} 
    } 


    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, 
      Authentication authResult) throws IOException, ServletException { 

     if (logger.isDebugEnabled()) { 
      logger.debug("Authentication success. Updating SecurityContextHolder to contain: " + authResult); 
     } 

     SecurityContextHolder.getContext().setAuthentication(authResult); 

     getRememberMeServices().loginSuccess(request, response, authResult); 

     // Fire event 
     if (this.eventPublisher != null) { 
      eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); 
     } 

     getSuccessHandler().onAuthenticationSuccess(request, response, authResult); 
} 
    } 

Việc thực hiện cung cấp dịch vụ tùy chỉnh như sau -

public class CustomAuthenticationProvider implements AuthenticationProvider, InitializingBean { 

private final static Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class); 

private AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> preAuthenticatedUserDetailsService = null; 
/** 
* 
*/ 
public Authentication authenticate(Authentication authentication) throws AuthenticationException { 

    if (!supports(authentication.getClass())) { 
     return null; 
    } 

    if (logger.isDebugEnabled()) { 
     logger.debug("PreAuthenticated authentication request: " + authentication); 
    } 

    if (authentication.getPrincipal() == null) { 
     logger.debug("No pre-authenticated principal found in request."); 
     return null; 
    } 

    UserDetails ud = preAuthenticatedUserDetailsService.loadUserDetails((PreAuthenticatedAuthenticationToken)authentication); 

    PreAuthenticatedAuthenticationToken result = 
      new PreAuthenticatedAuthenticationToken(ud, authentication.getCredentials(), ud.getAuthorities()); 
    result.setDetails(authentication.getDetails()); 

    return result; 

} 

@Override 
public void afterPropertiesSet() throws Exception { 
    // TODO Auto-generated method stub 
} 

@Override 
public boolean supports(Class<?> authentication) { 
    return PreAuthenticatedAuthenticationToken.class.isAssignableFrom(authentication); 
} 

/** 
* @return the preAuthenticatedUserDetailsService 
*/ 
public AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> getPreAuthenticatedUserDetailsService() { 
    return preAuthenticatedUserDetailsService; 
} 

/** 
* @param preAuthenticatedUserDetailsService the preAuthenticatedUserDetailsService to set 
*/ 
public void setPreAuthenticatedUserDetailsService(
     AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> preAuthenticatedUserDetailsService) { 
    this.preAuthenticatedUserDetailsService = preAuthenticatedUserDetailsService; 
} 
} 

Chúng tôi cũng đã cấu hình xử lý xác thực tùy chỉnh thành công để chuyển hướng người dùng cho URL thích hợp khi xác thực -

public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { 

/** 
* redirect user to appropriate home page based on user role 
*/ 
@Override 
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException { 

    Set<GrantedAuthority> authorities = ((UserDetails)authentication.getPrincipal()).getAuthorities(); 
    if(CollectionUtils.isNotEmpty(authorities)){ 
     GrantedAuthority role = getHighestRole(authorities); 
     String targetURL = getTargetURL(role); 
     if (targetURL != null) { 
      log.debug("Redirecting to target Url: " + targetURL); 
      getRedirectStrategy().sendRedirect(request, response, targetURL); 
      return; 
     } 
    } 

    super.onAuthenticationSuccess(request, response, authentication); 

} 
    } 

Các tập tin mùa xuân an ninh cấu hình giống như dưới đây -

<?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:security="http://www.springframework.org/schema/security" 
xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-3.1.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" pattern="/sso/*" entry-point-ref="http403ForbiddenEntryPoint" access-denied-page="/accessdenied.action" > 
    <security:anonymous enabled="false"/> 
    <security:custom-filter position="BASIC_AUTH_FILTER" ref="defaultBasicAuthFilter" /> 
    <security:expression-handler ref="expressionHandler"/> 
</security:http> 

<security:http use-expressions="true" auto-config="false" pattern="/rcd/associate/*" entry-point-ref="http403ForbiddenEntryPoint" access-denied-page="/accessdenied.action"> 
    <security:intercept-url pattern="/saml/sso/*" access="IS_AUTHENTICATED_ANONYMOUSLY"/> 
     <security:custom-filter position="BASIC_AUTH_FILTER" ref="defaultBasicAuthFilter" /> 
    <security:expression-handler ref="expressionHandler"/> 
</security:http> 

<bean id="http403ForbiddenEntryPoint" 
    class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" /> 


<bean id="expressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"> 
    <property name="permissionEvaluator" ref="customPermissionEvaluator" /> 
</bean> 

<bean id="defaultBasicAuthFilter" 
    class="com.example.security.authentication.DefaultAuthenticationProcessingFilter"> 
    <property name="authenticationManager" ref="authenticationManager" /> 
    <property name="authenticationSuccessHandler" ref="successRedirectHandler"/> 
    <property name="AuthenticationFailureHandler" ref="failureHandler"></property> 
</bean> 

<bean id="authProvider" 
class="com.example.security.authentication.CustomAuthenticationProvider"> 
    <property name="preAuthenticatedUserDetailsService"> 
     <bean id="userDetailsServiceWrapper" 
      class="org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper"> 
      <property name="userDetailsService" ref="userDetailsService" /> 
     </bean> 
    </property> 
</bean> 

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

<bean id="userDetailsService" class="com.example.security.authorization.UserDetailsServiceImpl" /> 

<bean id="successRedirectHandler" 
     class="com.example.security.authentication.CustomAuthenticationSuccessHandler"> 
     <property name="defaultTargetUrl" value="/user1/user1LandingPage.action"/> 
    </bean> 

<bean id="failureHandler" 
     class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"> 
    <property name="defaultFailureUrl" value="/accessdenied.action"/> 
</bean> 

Chúng tôi cũng đã cấu hình web.xml

<listener> 
    <listener-class> 
     org.springframework.web.context.ContextLoaderListener 
    </listener-class> 
</listener> 

<context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value> 
     /WEB-INF/spring/spring-app-context.xml <!-- ,/WEB-INF/spring/security.xml --> 
    </param-value> 
</context-param> 

<servlet> 
    <servlet-name>example-dispatcher-servlet</servlet-name> 
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
    <init-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value>/WEB-INF/spring/mvc.xml</param-value> 
    </init-param> 
    <load-on-startup>1</load-on-startup> 
</servlet> 

<!-- Map all /example*.action requests to the example-dispatcher-servlet for handling --> 
<servlet-mapping> 
    <servlet-name>example-dispatcher-servlet</servlet-name> 
    <url-pattern>*.action</url-pattern> 
</servlet-mapping> 

<welcome-file-list> 
    <welcome-file>/rcd/pages/index.jsp</welcome-file> 
</welcome-file-list> 

<listener> 
    <listener-class>com.example.HttpSessionListenerImpl</listener-class> 
</listener> 


<!-- Spring Security --> 
<filter> 
    <filter-name>springSecurityFilterChain</filter-name> 
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter> 

<filter-mapping> 
    <filter-name>springSecurityFilterChain</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 
</web-app> 

Chúng tôi đang sử dụng vào mùa xuân và mùa xuân 3.1.3 an ninh 3.1.3 On mỗi người dùng đăng nhập phiên mới sẽ được tạo và bối cảnh bảo mật nên được đặt tương ứng. Nhưng nó xảy ra trong trường hợp của tôi. Tôi đã kiểm tra debuggin ứng dụng của mình và thấy rằng phiên mới không được tạo ra khi người dùng đăng nhập. Có thể tôi đang thiếu nó ở đâu đó. Tôi không tìm thấy bất kỳ giải pháp có liên quan ở bất cứ đâu.

Bất kỳ trợ giúp nào về vấn đề này sẽ được đánh giá cao nhất.

Cảm ơn.

+0

cố định đây là kiện sử dụng – Ekanath

+4

như thế nào? Vui lòng thêm câu trả lời của bạn. –

+1

@Ebanath, bạn mong đợi những người khác giúp bạn nhưng không chia sẻ sự cố, tại sao? –

Trả lời

1

kẻ Xin lỗi, tôi đã không nhìn vào câu hỏi trong một thời gian dài mặc dù tôi đã giải quyết vấn đề này sau đó và thời gian riêng của mình -

tôi đã sử dụng securityContextPersistenceFilter trong phần tử và cấu hình như dưới đây -

<security:http> 
<security:custom-filter before="SECURITY_CONTEXT_FILTER" ref="securityContextPersistenceFilter"/> 

....

<bean id="securityContextPersistenceFilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter"> 
    <property name="forceEagerSessionCreation" value="true"></property> 
    <property name="securityContextRepository" ref="httpSessionSecurityContextRepository"/> 
</bean> 

<bean id="httpSessionSecurityContextRepository" class="org.springframework.security.web.context.HttpSessionSecurityContextRepository"> 
<property name="allowSessionCreation" value="false" /> 
</bean> 
+0

tôi có yêu cầu tương tự, bạn có thể xem xét vấn đề của tôi http://stackoverflow.com/questions/34269682/spring-security-handling-sso-and-db-users – sumedha