Primefaces Spring boot - провайдер аутентификации вызывается дважды - PullRequest
0 голосов
/ 03 февраля 2020

Я создаю приложение с весенней загрузкой (war) и простыми лицами. Я создал логин с пользовательским провайдером аутентификации. Когда мое приложение обрабатывает учетные данные, Spring проверяет их дважды. Почему?

My packages

ColombianApplication. java

@Configuration
@EnableJpaRepositories("com.colombian.online.repository")
@EntityScan("com.colombian.online.entity")
@ComponentScan("com.colombian.online")
@SpringBootApplication
public class ColombianApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(ColombianApplication.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(ColombianApplication.class);
    }

}

CustomAutheticationProvider. java

    @Component
    public class CustomAuthenticationProvider implements AuthenticationProvider {

        @Autowired
        private LoginService loginService;

        @Override
        public Authentication authenticate(Authentication auth) throws AuthenticationException {

            Usuario usuario = getCurrentUser();
            if (usuario == null) {
                String username = auth.getName();
                String password = auth.getCredentials().toString();

                Usuario usuarioQuery = loginService.findUserByCredentials(username, password);

                if (usuarioQuery == null) {
                    throw new UsernameNotFoundException("User not exist or your credentials are incorrect");
                }
                return new UsernamePasswordAuthenticationToken(usuarioQuery, password);
            }

            return new UsernamePasswordAuthenticationToken(usuario
                    , usuario.getPwd());
        }

        @Override
        public boolean supports(Class<?> type) {
            return type.equals(UsernamePasswordAuthenticationToken.class);
        }

        public Usuario getCurrentUser() {
            if (SecurityContextHolder.getContext().getAuthentication() != null) {
                Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                if (principal instanceof String) {
                    return null;
                }
                return (Usuario) principal;
            } else {
                return null;
            }

        }

    }


CustomContextInitializer.java
@Configuration
public class CustomContextInitializer  {

    @Bean
    public ServletContextInitializer servletContextInitializer() {
        return servletContext -> {
            servletContext.setInitParameter("com.sun.faces.forceLoadConfiguration", Boolean.TRUE.toString());
            servletContext.setInitParameter("primefaces.THEME", "nova-light");
        };
    }

    @Bean
    public ServletRegistrationBean servletRegistrationBean() {
        ServletRegistrationBean registration = new ServletRegistrationBean<>(new FacesServlet(), "*.xhtml");
        registration.setName("Faces Servlet");
        registration.setLoadOnStartup(1);
        return registration;
    }

    @Bean
    public ServletListenerRegistrationBean<ConfigureListener> jsfConfigureListener() {
        return new ServletListenerRegistrationBean<>(new ConfigureListener());
    }

}

SecurityConfiguration. java

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests()
                .antMatchers("/resources/**", "/javax.faces.resource/**", "/"
                ).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/").failureUrl("/?error=true")
                .defaultSuccessUrl("/home")
                .and()
                .logout().logoutUrl("/logout").permitAll().logoutSuccessUrl("/");
    }

    @Bean
    public FilterRegistrationBean rewriteFilter() {
        FilterRegistrationBean rwFilter = new FilterRegistrationBean(new RewriteFilter());
        rwFilter.setDispatcherTypes(EnumSet.of(DispatcherType.FORWARD, DispatcherType.REQUEST,
                DispatcherType.ASYNC, DispatcherType.ERROR));
        rwFilter.addUrlPatterns("/*");
        return rwFilter;
    }

}

My pom. xml

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- Primefaces with spring -->
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>7.0</version>
        </dependency>
        <!--dependency>
            <groupId>org.joinfaces</groupId>
            <artifactId>joinfaces-dependencies</artifactId>
            <version>4.1.1</version>
            <type>pom</type>
        </dependency-->
        <!-- Pretty faces -->
        <dependency>
            <groupId>org.ocpsoft.rewrite</groupId>
            <artifactId>rewrite-servlet</artifactId>
            <version>3.4.4.Final</version>
        </dependency>
        <!-- Lombok --> 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- Loggers -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>


        <!-- Spring tests -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.1.1-b04</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.1.1-b04</version>
            <type>jar</type>
        </dependency>
    </dependencies>

Проект не имеет сети. xml. Я использую библиотеку ocp.

Я исправил проблему, проверив текущего пользователя из SecurityContextHolder и отправив те же учетные данные.

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