Spring 4 Security + CORS + AngularJS-奇怪的重定向

时间:2019-02-13 07:35:21

标签: angularjs spring spring-security cors

我的Spring后端和AngularJS前端存在问题。作为信息,我对Spring Security还是一个新手,还可以从这个项目中学习。

我没有使用SpringBoot。两者都可以单独工作,并且应该能够在单独的机器上运行。我的前端ATM通过 https://localhost:3000 上的gulp服务器在本地运行,后端在 https://localhost:8443/context 上的Tomcat中运行。我已经用Java设置了CORSFilter

到目前为止,太好了。如果启动前端,则会调用后端以获取资源,并且正在登录页面。如果我选择登录,则按预期的那样将呼叫https://localhost:8443/context/login但是:在后端处理完登录后,后端会重定向到 https://localhost:8443/context 而不是 https://localhost:3000 >,这当然会创建404并导致登录失败(前端)。我只是找不到在哪里进行此奇怪的重定向。

SpringSecurityConfig

private static final String C440_LOGIN = "/login";
private static final String c440_START_PAGE = "/index.html";
private static final String FAVICON_ICO = "/favicon.ico";

@Override
protected void configure(HttpSecurity http) throws Exception {
    // HttpSecurity workHttp = http.addFilterBefore(new CORSFilter(), SessionManagementFilter.class); does not work!
    HttpSecurity workHttp = http.addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class);
    workHttp.addFilterBefore(new CookieFilter(), ChannelProcessingFilter.class);
    workHttp.addFilterBefore(getUsernamePasswordPortalAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

    // set authorizations
    workHttp = authorizeRequests(http);
    // login handling
    workHttp = formLogin(workHttp);
    // exception handling
    workHttp = exceptionHandling(workHttp);
    // logout handling
    workHttp = logout(workHttp);
    // cookie handling
    workHttp = rememberMe(workHttp);

    // disable caching because if IE11 webfonds bug
    // https://stackoverflow.com/questions/7748140/font-face-eot-not-loading-over-https
    http.headers().cacheControl().disable();

    csrf(workHttp);
}

/**
 * Configures request authorization.
 *
 * @param http The security configuration.
 * @return The configured security configuration.
 * @throws Exception is throws if the configuration fails.
 */
protected HttpSecurity authorizeRequests(HttpSecurity http) throws Exception {
    return http
        .authorizeRequests()

        // secured pages
        .antMatchers("/", getCustomerdWebRessourceSecuredPath()).authenticated()

        // common resources
        .antMatchers("/app/**").permitAll()
        .antMatchers("/profiles/**").permitAll()
        .antMatchers("/captcha/**").permitAll()

        .antMatchers("/", getCustomerRessourcePath()).permitAll()
        .antMatchers("/", getCustomerWebRessourcePath()).permitAll()

        .antMatchers("/", c440_START_PAGE).permitAll()
        .antMatchers("/", FAVICON_ICO).permitAll()
        .antMatchers(C440_LOGIN).permitAll()

        // frontend services
        .antMatchers("/services/userService/**").permitAll()
        .antMatchers("/services/applicationService/**").permitAll()
        .antMatchers("/services/textContentService/**").permitAll()
        .antMatchers("/services/textContentBlockService/**").permitAll()
        .antMatchers("/services/menuItemService/**").permitAll()
        .antMatchers("/services/calculatorService/**").permitAll()

        .anyRequest().authenticated()
        .and();
}

private String getCustomerRessourcePath() {
    return "/resources/app-" + portalFrontendBase + "/**";
}

private String getCustomerWebRessourcePath() {
    return "/app-" + portalFrontendBase + "/**";
}

private String getCustomerdWebRessourceSecuredPath() {
    return "/app-" + portalFrontendBase + "/secure/**";
}

/**
 * Configures form login.
 *
 * @param http The security configuration.
 * @return The configured security configuration.
 * @throws Exception is throws if the configuration fails.
 */
protected HttpSecurity exceptionHandling(HttpSecurity http) throws Exception {
    return http
        .exceptionHandling()
        .authenticationEntryPoint((request, response, authException) -> {
            if (authException != null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                /**
                 * IMPORTANT: do not redirect the requests. The front-end will be responsible to do this.
                 * Otherwise the unauthorized status cannot be caught in the front-end correctly.
                 */
                return;
            }
        })
        .and();
}

/**
 * Configures form login.
 *
 * @param http The security configuration.
 * @return The configured security configuration.
 * @throws Exception is throws if the configuration fails.
 */
protected HttpSecurity formLogin(HttpSecurity http) throws Exception {
    return http
        .formLogin()
            .loginPage(c440_START_PAGE)
            .successHandler(getAuthenticationSuccessHandler())
            .failureHandler(getAuthenticationFailureHandler())
            .loginProcessingUrl(C440_LOGIN)
            .permitAll()
            .and();
}

/**
 * Configures logout.
 *
 * @param http The security configuration.
 * @return The configured security configuration.
 * @throws Exception is throws if the configuration fails.
 */
protected HttpSecurity logout(HttpSecurity http) throws Exception {
    return http
        .logout()
            .logoutUrl(portalLogoutURL)
            .addLogoutHandler(getLogoutHandler())
            .logoutSuccessHandler(getLogoutSuccessHandler())
            .invalidateHttpSession(true)
            .and();
}

@Bean
public UsernamePasswordPortalAuthenticationFilter getUsernamePasswordPortalAuthenticationFilter() throws Exception {
    UsernamePasswordPortalAuthenticationFilter customFilter = new UsernamePasswordPortalAuthenticationFilter();
    customFilter.setAuthenticationManager(authenticationManagerBean());
    return customFilter;
}

UsernamePasswordPortalAuthenticationFilter.java

    @PropertySource(value = {"classpath:application.properties"})
    public class UsernamePasswordPortalAuthenticationFilter extends 
    UsernamePasswordAuthenticationFilter {
    private Logger log = Logger.getLogger(this.getClass());

    @Value("${captchaActive}")
    private boolean captchaActive;

    @Override
    public AuthenticationManager getAuthenticationManager() {
        return super.getAuthenticationManager();
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        UsernamePasswordPortalAuthenticationToken authRequest = getAuthenticationTokenFromRequest(request);
        return getAuthenticationManager().authenticate(authRequest);
    }

    /**
     * Reads the UsernamePasswordPortalAuthenticationToken from the data of the request.
     *
     * @param request The request to read the data from.
     * @return The authentication token.
     * @throws AuthenticationException is thrown if the data cannot be read.
     */
    public UsernamePasswordPortalAuthenticationToken getAuthenticationTokenFromRequest(final HttpServletRequest request) throws AuthenticationException {
        StringBuffer buf = new StringBuffer();
        String line = null;

        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                buf.append(line);
            }

            UsernamePasswordPortalAuthenticationToken loginDataWithCaptcha =
                new ObjectMapper().readValue(buf.toString(), UsernamePasswordPortalAuthenticationToken.class);

            if (this.captchaActive) {
                String answer = (String) request.getSession().getAttribute("COLLPHIRCAPTCHA");

                List<CaptchaCookieDto> captchaCookieDtos;
                captchaCookieDtos = (List<CaptchaCookieDto>) request.getAttribute("captchaCookies");

                CaptchaCookieDto captchaCookieDto = captchaCookieDtos.stream().filter(captchaCookie -> captchaCookie.getUsername().equals(
                    loginDataWithCaptcha.getUsername())).findAny().orElse(null);

                if (captchaCookieDto != null && captchaCookieDto.getCounter() >= 2) {
                    if (answer.equals(loginDataWithCaptcha.getConfirmCaptcha())) {
                        return new ObjectMapper().readValue(loginDataWithCaptcha.loginDataToStringWithoutCaptcha(),
                            UsernamePasswordPortalAuthenticationToken.class);
                    } else {
                        throw new BadCredentialsException("invalid data");
                    }
                } else {
                    return new ObjectMapper().readValue(loginDataWithCaptcha.loginDataToStringWithoutCaptcha(),
                        UsernamePasswordPortalAuthenticationToken.class);
                }
            } else {
                return new ObjectMapper().readValue(loginDataWithCaptcha.loginDataToStringWithoutCaptcha(), UsernamePasswordPortalAuthenticationToken.class);
            }


        } catch (Exception e) {
            throw new BadCredentialsException("invalid data");
        }

    }

}

我尝试更改两个自定义过滤器(CORSFilterCookieFilter)的顺序,或将CORSFilter放在其他位置(addFilterBefore SessionManagementFilter不可以,如果我这样做的话,由于缺少CORS标头和几乎其他所有内容,登录呼叫将无法工作...

我还尝试使用来自https://www.baeldung.com/spring_redirect_after_loginauthsuccesshandler中的想法,在这里我只是获得了请求origin标头(应该是前端URL https://localhost:3000)进行重定向回到它:

@Component
public class MyTestAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private Logger LOG = Logger.getLogger(this.getClass());
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    public MyTestAuthenticationSuccessHandler() {
        super();
        setUseReferer(true);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException {
        LOG.info("onAuthenticationSuccess");
        SecurityContextHolder.getContext().setAuthentication(auth);

        handle(request, response, auth);
    }

    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException {

        String targetUrl = determineTargetUrl(request);

        if (response.isCommitted()) {
            LOG.info("Response has already been committed. Unable to redirect to " + targetUrl);
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(HttpServletRequest request) {
        return request.getHeader("Origin");
    }
}

但仍然无法正常工作。

此外,如果我尝试调试后端并在authsuccesshandlerauthfailurehandler内设置断点,它仍然不会在那里停止。它不应该就此停止吗?

.formLogin()
        .loginPage(c440_START_PAGE)
        .successHandler(getAuthenticationSuccessHandler())
        .failureHandler(getAuthenticationFailureHandler())
        .loginProcessingUrl(C440_LOGIN)
        .permitAll()
        .and();

我真的不知道此重定向发生在哪里以及为什么不使用我的新authsuccesshandler

更新07.03.19:即使我同时部署了前端和后端,似乎也根本没有调用 successhandler URL作为捆绑的WAR文件,可以使登录再次生效。奇怪的是,即使我从.formLogin()内部的configure方法中删除了 SecurityConfig 东西,登录仍然有效。因此,我想似乎所有的魔术都在 AuthenticationProvider 中发生,在我们的自定义 UsernamePasswordAuthenticationFilter 中被调用:

UsernamePasswordAuthenticationFilter

[...]
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    UsernamePasswordPortalAuthenticationToken authRequest = getAuthenticationTokenFromRequest(request);
    return getAuthenticationManager().authenticate(authRequest);
}
[...]

AuthenticationProvider

[...]
@Override
public CollphirAuthentication authenticate(Authentication authentication) throws AuthenticationException {

    if (authentication == null) {
        throw new IllegalArgumentException("authentication");
    }

    if (UsernamePasswordPortalAuthenticationToken.class.isAssignableFrom(authentication.getClass())) {
        UsernamePasswordPortalAuthenticationToken clientAuthentication = (UsernamePasswordPortalAuthenticationToken) authentication;

        CollphirUser user = getUserService().loginUser(
                clientAuthentication.getName(), clientAuthentication.getCredentials().toString(), clientAuthentication.getPortal(), clientAuthentication.getArbeitgeber());
        CollphirAuthentication auth = null;

        if (user == null || user.getBenutzerkennung() == null || user.getCOLRolle() == null) {
            LOG.info("authentication failed");
            Notification[] notifications = user.getNotifications();
            String msg = null;

            if (notifications != null && notifications[0] != null && notifications[0].getText() != null) {
                msg = notifications[0].getText();
            }

            throw new BadCredentialsException(msg);
        }
        Referenz arbeitgeberReference = getArbeitgeberReference(user, clientAuthentication.getPortal(), clientAuthentication.getArbeitgeber());

        auth = new CollphirAuthentication(user, arbeitgeberReference);
        auth.setArbeitgeber(getArbeitgeber( arbeitgeberReference));

        LOG.debug("is authenticated: " + auth.isAuthenticated());

        return auth;
    }

    throw new BadCredentialsException("type");
}
[...]

所以我的猜测是:在 UsernamePasswordPortalAuthenticationFilter AuthenticationProvider 中的某个地方进行了重定向。如果我考虑一下,在通过REST进行后端调用的AngularJS前端中,重定向根本没有任何意义,对吗?后端不应该只是发送回状态代码或AngularJS控制器可以评估以更改状态或显示错误消息的内容吗?

看来,此应用程序中的整个登录过程确实很奇怪。我无法想象通常不使用 .formLogin() .successHandler() 吗?问题是,我没有AngularJS前端和Spring Security后端的最佳实践示例作为比较...

1 个答案:

答案 0 :(得分:0)

您是否使用Springs默认的AuthenticationSuccessHandler?我认为该处理程序只是重定向到应用程序的基本路径,并且如果您的前端位于另一个上下文或URL上,它将不起作用。因此,您必须在成功登录回到前端后执行重定向。

看看此页面:https://www.baeldung.com/spring-security-redirect-login

在这里您可以找到处理该情况的几种可能性。