Приложение Spring Boot перенаправляет на http URL после успешного входа - PullRequest
1 голос
/ 09 ноября 2019

У меня есть приложение весенней загрузки со следующей конфигурацией безопасности.

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      String[] csp = {"default-src 'self'",
                "script-src 'self'",
                "style-src 'self'",
                "img-src 'self'", 
                "font-src 'self'",
                "child-src 'self'",
                "form-action 'self' ",
                "frame-ancestors 'none'",
                "manifest-src 'self'"
        };

      http
        .addHeaderWriter(new StaticHeadersWriter("Content-Security-Policy", String.join(";", csp)))
        .loginPage("/login")
        .loginProcessingUrl("/login")
        .defaultSuccessUrl("/landing");
    }
}

Я нажму на URL https://my-app.com/login, введите правильное имя пользователя и пароль и нажмите «Войти». Я получаю сообщение об ошибке:

Отказался отправлять данные формы в http://my -app.com / , поскольку он нарушает следующую директиву политики безопасности содержимого:действие "Я" ".

Я не уверен, почему мое приложение перенаправляет на http URL вместо https один. Я хотел бы перенаправить успешный вход на https URL

Ответы [ 2 ]

1 голос
/ 10 ноября 2019

Это не связано с самой Spring Boot. Вы должны настроить свой веб-сервер или сервер приложений (в данном случае, я полагаю, встроенный tomcat). Не могли бы вы поделиться своими application.properties? Вы настроили SSL? Если да, вы можете добиться перенаправления https с помощью метода postProcessContext TomcatEmbeddedServletContainerFactory, создав Бин следующим образом:

TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
    @Override
    protected void postProcessContext(Context context) {
        SecurityConstraint securityConstraint = new SecurityConstraint();
        securityConstraint.setUserConstraint("CONFIDENTIAL");
        SecurityCollection collection = new SecurityCollection();
        collection.addPattern("/*");
        securityConstraint.addCollection(collection);
        context.addConstraint(securityConstraint);
    }
};
0 голосов
/ 12 ноября 2019

WebSecurityConfigurerAdapter нуждается в хирургической настройке и зависит от структуры.

Например, если ваша структура автоматически создает страницу с именем / аутентификация вместо / login и ресурсы находятся в папке / media вместоclassic / style / font, ваша конфигурация будет сильно отличаться.

В вашем случае Thymeleaf - это классический фреймворк, а его настройки безопасности основаны на spring-framework и хорошо документированы:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private LoggingAccessDeniedHandler accessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers(
                            "/",
                            "/js/**",
                            "/css/**",
                            "/img/**",
                            "/webjars/**").permitAll()
                    .antMatchers("/user/**").hasRole("USER")
                    .anyRequest().authenticated()
                .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
                .and()
                .logout()
                    .invalidateHttpSession(true)
                    .clearAuthentication(true)
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/login?logout")
                    .permitAll()
                .and()
                .exceptionHandling()
                    .accessDeniedHandler(accessDeniedHandler);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER")
            .and()
                .withUser("manager").password("password").roles("MANAGER");
    }

}

Проверьте ссылки:

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...