проблема в отправке j_spring_security_check из управляемого компонента в весенней безопасности? - PullRequest
0 голосов
/ 01 февраля 2020

Я хочу настроить JSF (primefaces) с пружиной, но у меня проблема с использованием безопасности пружины. по какой-то причине (проверяя капчу позже) я отправляю сообщение "j_spring_security_check" от управляемого бина, после вставки имени пользователя и пароля и т. д. и отправки запроса вызывается метод управляемого боба, а затем выдается сообщение об ошибке удара в консоли, и поэтому выполняется аутентификация ошибка:

01 февраля 2020 г. 17:29:06 org.springframework.web.servlet.PageNotFound noHandlerFound

ПРЕДУПРЕЖДЕНИЕ. Нет сопоставления для POST / common / form / j_spring_security_check

1 февраля 2020 г. 17:29:06 IRST Предупреждение org.springframework.web.servlet.PageNotFound BEA-000000 Нет сопоставления для POST / common / form / j_spring_security_check

Кто-нибудь может помочь, что я должен сделать, чтобы решить эту проблему (предпочтительно java config)? спасибо.

login.x html

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core"
      xmlns:p="http://primefaces.org/ui">

<h:head>
    <title>Login</title>
</h:head>

<h:body>
    <h:form id="loginFormId" prependId="false">

        <p:panelGrid columns="1" styleClass="ui-fluid center ui-noborder">
            <h2>Please login</h2>

            <p:outputLabel value="Login failed!" styleClass="red"
                           rendered="${!empty param['error']}" />

            <p:inputText id="username" placeholder="User name" />
            <p:password id="password" placeholder="Password" />

            <p:commandButton value="Login" ajax="false" action="#{loginCtrl.login}"/>
        </p:panelGrid>

    </h:form>
</h:body>
</html>

WebInitializer. java

public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{WebConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[0];
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

WebConfig. java

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "mcom")
@ComponentScan(basePackages = {"mcom.*"})
@Import(SecurityConfig.class)
@PropertySource("classpath:mcom/m2/common/config/Application.properties")
public class WebConfig {

    @Autowired
    private Environment environment;

    @Bean
    DataSource dataSource(){
        System.out.println("WebConfig.dataSource");

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("db.driver"));
        dataSource.setUrl(environment.getRequiredProperty("db.url"));
        dataSource.setUsername(environment.getRequiredProperty("db.username"));
        dataSource.setPassword(environment.getRequiredProperty("db.password"));

        return dataSource;

    }

    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(DataSource dataSource){
        System.out.println("WebConfig.entityManagerFactoryBean");

        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan("mcom");

        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.setProperty("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.setProperty("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));

        entityManagerFactoryBean.setJpaProperties(properties);

        return entityManagerFactoryBean;
    }

    @Bean
    JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory){
        System.out.println("WebConfig.transactionManager");

        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);

        return transactionManager;
    }

SecurityInitializer. java

public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}

SecurityConfig. java

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder builder) throws Exception {
        System.out.println("SecurityConfig.configureGlobal");

        try {
            builder.inMemoryAuthentication().withUser("kobe")
                    .password("{noop}1234").roles("USER").and()
                    .withUser("james").password("{noop}1414").roles("ADMIN", "USER");
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }



    @Override
    public void configure(HttpSecurity http) throws Exception{
        System.out.println("SecurityConfig.configure");

        try {
            http.addFilterBefore(new customUsernamePasswordAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

            http.authorizeRequests().antMatchers("/javax.faces.resource/**","/form/login.xhtml").permitAll().anyRequest().authenticated();
            http.formLogin().loginPage("/form/login.xhtml").loginProcessingUrl("/j_spring_security_check").permitAll().defaultSuccessUrl("/form/home.xhtml").failureUrl("/form/login.xhtml?error=true");
            http.csrf().disable();

        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }
}

LoginCtrl. java

try {
            ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
            HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            RequestDispatcher dispatcher = ((ServletRequest)context.getRequest()).getRequestDispatcher("j_spring_security_check");
            dispatcher.forward((ServletRequest)context.getRequest(), (ServletResponse)context.getResponse());
            FacesContext.getCurrentInstance().responseComplete();

        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

web. xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
          http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>javax.faces.FACELETS_LIBRARIES</param-name>
        <param-value>/WEB-INF/springsecurity.taglib.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

</web-app>

Лиц-Конфиг. xml

<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
    http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
    <application>
        <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
    </application>
</faces-config>
...