覆盖现有的Spring Security身份验证

时间:2017-02-27 09:18:19

标签: java spring authentication spring-security pre-authentication

如何通过调用Web服务覆盖现有的Spring Security身份验证,当它失败时,需要重定向某些第三方登录页面。

要调用此身份验证Web服务,我需要获取一些ServletRequest参数,对于重定向,我需要访问ServletResponse。

因此,我需要找到一些使用ServletRequest和ServletResponse参数的Authentication方法。

但是,我仍未找到这样的ProcessingFilter或AuthenticationProvider。

根据Spring Security基础,似乎我必须覆盖与AuthenticationProvider相关的身份验证方法。

根据用例,我必须实现Spring Security Pre-authentication,

但问题是PreAuthenticatedAuthenticationProvider相关的'authenticate'方法只有Authentication参数。

PreAuthenticatedAuthenticationProvider

public class PreAuthenticatedAuthenticationProvider implements
        AuthenticationProvider, InitializingBean, Ordered {

    public Authentication authenticate(Authentication authentication) {}

}

作为解决方案,是否有可能使用AuthenticationFailureHandler 的自定义实现?

感谢。

1 个答案:

答案 0 :(得分:0)

我已按照以下方式解决了问题,

  • 实施自定义AbstractPreAuthenticatedProcessingFilter

覆盖 doFilter 方法

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    try { 

        // Get current Authentication object from SecurityContext
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        // Call for third party WS when the Authenticator object is null
        if (auth == null) {

            logger.debug("doFilter : Proceed the authentication"); 

            String appId = "My_APP_ID";
            String redirectURL = request.getRequestURL().toString(); 

            // Call for third party WS for get authenticate 
            if (WS_Authenticator.isAuthenticated(appId, redirectURL)) { 

                // Successfully authenticated
                logger.debug("doFilter : WS authentication success");

                // Get authenticated username 
                String userName = WS_Authenticator.getUserName();               

                // Put that username to request
                request.setAttribute("userName", userName);

            } else {

                String redirectURL = WS_Authenticator.getAuthorizedURL();
                logger.debug("doFilter : WS authentication failed");
                logger.debug("doFilter : WS redirect URL : " + redirectURL);

                ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                ((HttpServletResponse) response).sendRedirect(redirectURL);

                // Return for bypass the filter chain 
                return;
            }   

        } else {
            logger.debug("doFilter : Already authenticated"); 
        }   

    } catch (Exception e) {
        logger.error("doFilter: " + e.getMessage());            
    }

    super.doFilter(request, response, chain);
    return;
}

覆盖 getPreAuthenticatedCredentials 方法

@Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {

    // Get authenticated username
    String[] credentials = new String[1];
    credentials[0] = (String) request.getAttribute("userName");

    return credentials;
}
  • 实施CustomAuthenticationUserDetailsS​​erviceImpl

覆盖 loadUserDetails 方法

public class CustomAuthenticationUserDetailsServiceImpl implements AuthenticationUserDetailsService<Authentication> {

    protected static final Logger logger = Logger.getLogger(CustomAuthenticationUserDetailsServiceImpl.class);

    @Autowired
    private UserDataService userDataService;

    public UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException {

        // Get authenticated username 
        String[] credentials = (String[]) token.getCredentials();
        String userName = credentials[0];

        try {

            // Get user by username
            User user = userDataService.getDetailsByUserName(userName); 

            // Get authorities username             
            List<String> roles = userDataService.getRolesByUserName(userName);          
            user.setCustomerAuthorities(roles);
            return user;

        } catch (Exception e) {
            logger.debug("loadUserDetails: User not found! " + e.getMessage());
            return null;
        }       
    }
}